简体   繁体   English

有没有一种方法可以基于单个值在html元素的多个数据属性内搜索数组?

[英]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');

http://jsfiddle.net/pWdSP/1/ http://jsfiddle.net/pWdSP/1/

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.

相关问题 根据元素中的索引值向 html 元素动态添加属性 - add attributes dynamically to the html element based on Index value in the element 如何根据多个数据属性过滤搜索结果 - How to filter search results based on multiple data attributes 是否有另一种方法来显示/隐藏基于 html5 数据属性的字段? - Is there another way to show / hide fields based on html5 data attributes? 基于多个键值对搜索对象数组的优化方法 - Optimized way to search an object array based on multiple key-value pairs 创建 HTML 元素并为其附加属性然后将其包装在另一个元素中的最有效方法是什么? - What is the most efficient way of creating an HTML element and appending attributes to it and then wrapping it inside of another element? HTML属性内JS中的双引号和单引号 - Double and single quotes in JS inside HTML attributes 如何在元素 html 内部添加元素数据属性值 - How to add element data attribute value inside of the element html 单个文本框元素中的多个字体属性 - Multiple font attributes within a single textbox element 有没有一种方法可以搜索以HTML中的某个字符串开头的属性 - Is there a way to search for attributes that start with a certain string in HTML 在单个元素上查找所有数据属性 - Find All Data Attributes on a Single Element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM