[英]Using Data Attribute Object as a Selector in jQuery
I have the following data attribute object: 我有以下数据属性对象:
<div data-vp="{
id: "vp-485858383",
customTwo: "test"
}">
</div>
I'm trying to target data-vp with the specific id value in jQuery: 我正在尝试使用jQuery中的特定id值来定位data-vp:
$(['data-vp with id:vp-485858383'].parent().find('.fa.fa-times').show();
I'm doing this so I can show only a specific instance of .fa.fa-times rather than all elements with the .fa.fa-times class. 我这样做是为了仅显示.fa.fa-times的特定实例,而不显示.fa.fa-times类的所有元素。
I know the selector above won't work obviously, but is it possible to target both data-vp along with the specific ID? 我知道上面的选择器显然不能正常工作,但是可以同时将data-vp和特定的ID作为目标吗?
You can use the attribute-contains selector for that: 您可以为此使用attribute-contains选择器:
$(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.
请注意,您的文字必须完全相同。
Another option is to filter the elements based on the data-vp attribute: 另一个选择是根据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.为此,您必须将
data-vp
属性的内容设置为有效的json字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.