Javascript 如何使用类名作为选择器来获取类成员的数据属性?
我有如下代码Javascript 如何使用类名作为选择器来获取类成员的数据属性?,javascript,jquery,html,custom-data-attribute,Javascript,Jquery,Html,Custom Data Attribute,我有如下代码 <div class="apples" data-id="1"></div> <div class="apples" data-id="2" id="secondDiv"></div> 我的问题是关于数据属性。单击时,我希望了解所单击的div的数据属性 这很有效 $secondDiv.dataid//返回2 这不是 $.apples[1].dataid//返回TypeError:$…[1]。数据不是函数 这没用, $.apples.
<div class="apples" data-id="1"></div>
<div class="apples" data-id="2" id="secondDiv"></div>
我的问题是关于数据属性。单击时,我希望了解所单击的div的数据属性
这很有效
$secondDiv.dataid//返回2
这不是
$.apples[1].dataid//返回TypeError:$…[1]。数据不是函数
这没用,
$.apples.dataid//返回1
如何使用类名获取div的数据属性?
代码中div的实际数量太大,无法为每个div提供唯一的HTML id
谢谢下面将记录单击的apple css类元素的数据id属性值:
$(".apples").on("click", function(){
console.log($(this).data("id"));
});
是jQuery方法,仅在jQuery对象包装器上可用
$.apples是一个jQuery对象包装器,因此具有数据方法
$.apples[1]是一个DOM对象,因此没有数据方法
那么,你可以
再次将DOM对象包装到jQuery对象中:
$$.apples[1].dataid;
使用,它将仅返回jQuery包装中所需的元素:
$.apples.eq1.dataid;
使用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>
哦很酷,谢谢!将在10min等待期之后接受回答:当然,很乐意帮助:@ JETBLUE:除非您有特定的需要将ID存储在jQuery的全局缓存中,考虑使用$Test.AtHATDATA ID,甚至更好地使用Test.GestAtditDATA ID。它更快并且不增加任何内存开销。@ BHOVO:是的。使用.get0与[0]基本相同。感谢您的帮助,我知道我之前说过我会接受您的答案,但@Oriol answer更详细地说明了发生了什么以及为什么。如果高兴,您可以接受我的答案,Thankst这多少有点像如果你想用一种更简单的方式来处理vanilla js,而不需要jQuery的话,试试看:谢谢你的解释!我永远也猜不到这两者之间的区别。
<!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>