我有以下数据属性对象:
<div data-vp="{
id: "vp-485858383",
customTwo: "test"
}">
</div>
我正在尝试使用 jQuery 中的特定 id 值定位 data-vp:
$(['data-vp with id:vp-485858383'].parent().find('.fa.fa-times').show();
我这样做是为了仅显示 .fa.fa-times 的特定实例,而不是所有具有 .fa.fa-times 类的元素。
我知道上面的选择器显然不会起作用,但是是否可以将 data-vp 与特定 ID 一起定位?
最佳答案
您可以为此使用属性包含选择器:
$(function() {
$('[data-vp*="id: vp-485858383"]').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-vp='{
id: vp-485858383,
customTwo: "test"
}'>
asdf
</div>
Note that your text must be exactly the same.
另一种选择是根据 data-vp 属性过滤元素:
$(function() {
$('[data-vp]').filter(function(i, el) {
return $(el).data('vp').id == 'vp-485858383';
}).css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-vp='{
"id": "vp-485858383",
"customTwo": "test"
}'>
asdf
</div>
<div data-vp='{
"id": "vp-123",
"customTwo": "test"
}'>
asdf
</div>
For that you must have the content of the
data-vp
attribute to be a valid json string.
关于javascript - 在 jQuery 中使用数据属性对象作为选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44123826/