Javascript 如何使用vanilla JS以单个值查询具有值数组的数据属性?
我有一系列的博客文章,其中包含一系列标签,作为Javascript 如何使用vanilla JS以单个值查询具有值数组的数据属性?,javascript,html,arrays,custom-data-attribute,Javascript,Html,Arrays,Custom Data Attribute,我有一系列的博客文章,其中包含一系列标签,作为数据标签html属性,例如[“foo”,“bar”,“baz”]。我希望查询包含在数据标记数组中的foo的DOM元素 标记示例: <li data-tags="['foo', 'bar', 'baz']">...</li> 甚至可以选择数组中包含特定值的元素吗 (仅限Vanilla JS,请不要jQuery)您可以使用CSS获取页面上的任何元素 即 使用href的[href] 获取数据类型为price的divdiv[data
数据标签
html属性,例如[“foo”,“bar”,“baz”]
。我希望查询包含在数据标记
数组中的foo
的DOM元素
标记示例:
<li data-tags="['foo', 'bar', 'baz']">...</li>
甚至可以选择数组中包含特定值的元素吗
(仅限Vanilla JS,请不要jQuery)您可以使用CSS获取页面上的任何元素 即 使用href的
[href]
获取数据类型为price的divdiv[data type=price]
var属性=['data-rel','type'];
attributes.forEach((at)=>{
document.querySelectorAll('['+at+']').forEach((元素)=>{
元素。追加(“”+at+“”);
});
});代码>
你好
世界
:-)
这里有一个解决您问题的普通js解决方案:
const posts = document.querySelectorAll('[data-tags]');
const fooPosts = [];
posts.forEach(post => {
if (/foo/.test(post.getAttribute('data-tags'))) {
fooPosts.push(post);
}
});
// output the filtered posts
console.log(fooPosts);
一个班轮备选方案:
document.querySelectorAll('[data-tags]').forEach(post => /foo/.test(post.getAttribute('data-tags')) && console.log(post));
或拆分:
document.querySelectorAll('[data-tags]').forEach(post =>
/foo/.test(post.getAttribute('data-tags')) && console.log(post));
请注意,如评论中所述,您的html标记无效。数据属性不应包含数组或对象之类的复杂数据结构。如建议的,考虑在数组数据上执行.Co(),并将其输出到属性[数据标记]中作为字符串。为了便于阅读,每个值都可以用逗号分隔
使用有效的标记,您的解决方案将略有不同:
const posts = document.querySelectorAll('[data-tags]');
const fooPosts = [];
posts.forEach(post => {
if (post.getAttribute('data-tags').indexOf('foo') > -1) {
fooPosts.push(post);
}
});
console.log(fooPosts);
上面的代码使用.indexOf()过滤DOM节点时速度也更快。
以下是可重用函数中的上述代码:
const filterNodesByAttr = (attr, tag) => {
let filtered = [];
const items = document.querySelectorAll(`[${attr}]`);
items.forEach(item => {
if (item.getAttribute(attr).indexOf(tag) > -1) {
filtered.push(item);
}
});
return filtered;
};
const fooPosts = filterNodesByAttr('data-tags', 'foo');
console.log(fooPosts);
总之,您需要的查询是
document.querySelectorAll('li[data-tags*=\'"foo"\']')
但是您必须确保html数组中的每个元素都用双引号括起来。您可以将其更改为单个报价,但请确保更新查询
您可以通过添加更多规则来搜索多个查询,如下所示
document.querySelectorAll('li[data-tags*=\'"foo"\']'+'[data-tags*=\'"bar"\']')
下面是一个基于您可能感兴趣的某个值应用这些查询的代码段。我确保使用您在问题中输入的相同html结构
编辑:
我又添加了一个函数queryAll,它允许进行值查询。因此,您可以搜索必须具有多个值的元素
函数条目(搜索){
变量字符串='“'+搜索+'”;
返回“[data tags*=\''+string+'\']”;
}
函数queryAll(){
var querys=Array.prototype.slice.call(参数).map(函数(a){
返回“[data tags*=\''+a+'\']”;
});
//示例:document.querySelectorAll('li[data tags*=\'“foo”\']);
returndocument.querySelectorAll('li'+querys.join('');
}
功能查询(搜索){
变量字符串='“'+搜索+'”;
//示例:document.querySelectorAll('li[data tags*=\'“foo”\']);
return document.querySelectorAll('li[data tags*=\''+string+'\'];
}
查询(“foo1”);//一里
查询(“foo”)//两里
queryAll(“foo1”、“bar1”)//一里
queryAll(“foo1”、“bar1Not”)//无任何内容
您能否显示足够多的HTML,以便我们能够准确地看到您需要搜索的内容类型,以及响应什么事件?请阅读和指南作为复习。请参阅css属性选择器文档:根据您的html,您可以使用[数据标记~=“foo”]
或[数据标记*=“foo”]
。值得指出的是,您的html是无效的,您不能使用用于引用字符串的同一分隔符在属性中分隔文本;另外:为什么它是一个字符串中的数组,而不是一个空格分隔的标记字符串?有趣的是,@kLabz建议的选择器*=
似乎可以与现有标记正常工作。不过,感谢您指出,用空格分隔的标签串是更好的做法。如果querySelectorAll
变得太慢,另一种方法是循环所有元素并检查它们的.dataset.tag
属性
document.querySelectorAll('li[data-tags*=\'"foo"\']'+'[data-tags*=\'"bar"\']')