如何使用 class 名称作为选择器来获取 class 成员的数据属性?

How can you get the data attribute of a class member using the classname as a selector?

我有如下代码,

<div class="apples" data-id="1"></div>
<div class="apples" data-id="2" id="secondDiv"></div>

每个 div 都有一个 onClick 事件侦听器。当我单击 div 时,会发生一些独特的事情,具体取决于单击的是哪个 div。例如,

$(".apples")[0].addEventListener("click", function(){
    console.log("first apple was clicked"); 
});

我的问题是关于 数据属性 。单击时,我想知道被单击的 div 的数据属性。

这有效,

$("#secondDiv").data("id"); //returns 2

这不是,

$(".apples")[1].data("id"); //returns TypeError: $(...)[1].data is not a function

这个没用,

$(".apples").data("id"); //returns 1

如何使用类名获取 div 的数据属性? 代码中 div 的实际数量太大,无法给每个人一个唯一的 HTML id,因此不实用。

谢谢

下面将记录点击的苹果 css class 元素的 data-id 属性值。:

 $(".apples").on("click", function(){
      console.log($(this).data("id")); 
 });

data 是一个 jQuery 方法,仅在 jQuery 对象包装器上可用。

$(".apples") 是一个 jQuery 对象包装器,因此具有 data 方法。

$(".apples")[1] 是一个 DOM 对象,因此没有 data 方法。

那么,你可以

  • 再次将 DOM 对象包裹在 jQuery 对象中:

    $($(".apples")[1]).data("id");
    
  • 使用 eq,这将 return 仅 jQuery 包装器中的所需元素:

    $(".apples").eq(1).data("id");
    
  • 使用vanilla-js读取数据属性:

    $(".apples")[1].dataset.id;
    $(".apples")[1].getAttribute('data-id');
    

这是我的代码!希望你喜欢:

<!DOCTYPE html>
<html lang = 'es'>
    <head>
        <title> MY TEST </title>
        <meta charset = 'utf-8'>
        <style>
            .apples{
                width: 300px;
                height: 300px;
                background-color: red;
            }
        </style>
    </head>
    <body>
        <div class="apples" data-id="1" id = 'firstDiv'>APPLE 1</div>
        <br>
        <div class="apples" data-id="2" id= 'secondDiv'>APPLE 2</div>
        <script>

            //Getting the references to the "apples"
            var apple1 = document.getElementById('firstDiv');
            var apple2 = document.getElementById('secondDiv');

            //Adding the events listeners
            apple1.addEventListener('click', doTheMagic);
            apple2.addEventListener('click', doTheMagic)

            function doTheMagic(e){
                alert('You clicked an apple ');
                var dataApple = e.target.getAttribute('data-id');
                alert('This apple has a value for his data-id of: ' + dataApple);
            }
        </script>
    </body>
</html>