[英]Is there a way to search an array inside multiple data attributes of an html element based on a single value?
I have an html element that uses arrays inside the data attribute 我有一个html元素,该元素在data属性内使用数组
<div data-area='["North America", "United Kingdom"]'>Test</div>
I have multiple data attributes pertaining to different "things" 我具有与不同“事物”有关的多个数据属性
<div data-area='["North America", "United Kingdom"]' data-job='["Programmer","Scientist"]'>test</div>
How can I go by searching through all the data attribute tags on the entire element based off of 1 value? 如何基于1值搜索整个元素上的所有数据属性标签?
I'm trying to use a selector rather than looping through each data attribute, Is this possible? 我正在尝试使用选择器,而不是遍历每个数据属性,这可能吗?
Here is an example plus a fiddle of what I've attempted. 这是一个例子,再加上我尝试过的东西。
// search all data attributes of a div element that contains the given value and apply a hidden class
// this should search every data attribute for "Programmer"
$('[data-*="Programmer"]').addClass('hidden');
I can only think of this solution: 我只能想到这种解决方案:
$('body *').addClass(function() {
var data = $(this).data();
for (var i in data) if (data.hasOwnProperty(i)) {
if (data[i].indexOf('Programmer') > -1) {
return;
}
}
return 'hidden';
});
http://jsfiddle.net/pWdSP/4/ http://jsfiddle.net/pWdSP/4/
It's not optimal since it iterates over all DOM nodes, but I don't see other way to select all the nodes that have data-*
attribute. 这不是最佳方法,因为它会遍历所有DOM节点,但是我看不到其他方法来选择所有具有data-*
属性的节点。
If there are some more precise criterias on what nodes should be checked - it's highly recommended to change a selector accordingly (instead of body *
) 如果对应该检查的节点有一些更精确的标准-强烈建议相应地更改选择器(而不是body *
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.