jQuery使用common关键字选择数据属性

我有两个元素,具有以下设置:

  

我使用下划线来遍历包含这些属性之一的任何元素,然后执行相关操作。

目前这样做是这样的

 _.each($('[data-placeholder-class], [data-placeholder-template]'), function cb(element) { // code goes here }) 

我不想定义每个数据属性来循环,而是想知道是否有一种方法可以选择包含公共关键字的所有属性,在本例中为占位符。 例如

 _.each($('[data-placeholder-*]'), function cb(element) { // code goes here }) 

任何人都知道这是否可行?

您可以考虑使用一个单独的函数来创建您的选择器,这样您就不必完全键入选择器(但是您必须编写函数)。

EQ:

 function getSelector() { return Array.prototype.map.call(arguments, function(key) { return '[data-placeholder-' + key + ']'; }).join(','); } 

这将返回您想要的选择器,并使用1 … N个参数。

 getSelector('class', 'template') // returns "[data-placeholder-template],[data-placeholder-class]" _.each($(getSelector('class', 'template')), function cb(element) { // code goes here }); 

您可以迭代元素集合的attributes ,如果元素.attributes.name与提供的字符串变量匹配,则将元素推送到数组

 var spans = document.querySelectorAll("span"); function filterAttrs(elems, attr, matches = []) { for (var elem of elems) { for (var attrs of elem.attributes) { // alternatively use `.indexOf()` or `RegExp()` // to match parts of string of `.name` or `.value` // of `.attributes` `NamedNodeMap` if (attrs.name.slice(0, attr.length) === attr) { matches.push({ "element": elem, "attr": { "name": attrs.name, "value": attrs.value } }) } } } return matches } var matches = filterAttrs(spans, "data-placeholder"); console.log(matches); matches.forEach(function(match) { match.element.textContent = "matches:" + JSON.stringify(match.attr); match.element.style.color = "green"; }); 
    data-not-placeholder-template   data-not-placeholder-template  

我知道这是一个jquery问题,但是由于XPath查询,有一种方法可以做到这一点:

starts-with() XPath函数就是这样做的。

所以查询//*[@*[starts-with(name(), 'data-placeholder')]]将为您提供所需的内容。

打开:

  '//' + // from root to anywhere in the tree '*' + // any kind of node '[@*' + // with any attribute '[starts-with(name(), "data-placeholder")]' + // which starts with "data-" ']' 
 function getElementsByStartOfAttribute(start_of_attr) { var query = document.evaluate("//*[@*[starts-with(name(), '" + start_of_attr + "')]]", document, null, XPathResult.ANY_TYPE, null); var elements = []; var el; while (el = query.iterateNext()) { elements.push(el); } return elements; } var placehodlers = getElementsByStartOfAttribute('data-placeholder'); console.log(placehodlers); $(placehodlers).css('background', 'green'); 
  should find me me too  data-not-placeholder-template   data-not-placeholder-template  
  var eles = $('span').filter(function() { for (var attrName in $(this).data()) { if (attrName.indexOf('placeholder') == 0) { return true; } } return false; }); console.log(eles); 

我希望这能帮到您 :)

示例HTML:

 test hahaha hahahahaha hahahahaha 

JS:

 $('span').filter(function(ndx, item){ var data = Object.keys($(item).data())[0]; // gets data name if (data === undefined) { return; } // checks if data starts with placeholder if (~(data.indexOf('placeholder'))) { // do anything to that item here return item; } }).css('color', 'green'); 

小提琴: 这里

希望这可以帮助! 🙂