以某个字符串开头的属性的jQuery选择器

4
我需要选择所有具有给定前缀的属性名称的元素 - 注意,我说的是属性名称,而不是值。例如:
<div data-abc-name="value">...</div>
<a href="..." data-abc-another="something">...</a>
<span data-nonabc="123">...</span>

在上述HTML中,我需要获取所有具有属性以 data-abc- 开头的元素 - 也就是说,diva
我该怎么做?
4个回答

3
这是我的解决方案 - Fiddle。您需要创建自己的jquery选择器。
jQuery.extend(jQuery.expr[':'], {
    attrStartsWith: function (el, _, b) {
        for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) {
            if(atts[i].nodeName.toLowerCase().indexOf(b[3].toLowerCase()) === 0) {
                return true; 
            }
        }

        return false;
    }
});

//e.g:
$('a:attrStartsWith("data-abc")').html('hello');
$('div:attrStartsWith("data-abc")').html('hello');

我最近不得不使用它。我在某个地方找到了答案,但是现在无法找到来源。如果有人知道,请告诉我,我会提供作者的所有权! - Loaf
这看起来很有前途。因此,要查找所有这样的元素,我会使用 $('*:attrStartsWith("data-abc-")') - Aleks G

1
你可以通过ES6这样做:

$('*').filter(function() {
  for (attr of this.attributes)
    if (attr.name.startsWith("data-abc"))
      return this;
});

在线演示(jsFiddle)


1
Array.from(document.querySelector('element').attributes).filter(x=>x.name.startsWith('attr-starts-with'))

0

我认为我们没有带有正则表达式的 jQuery 选择器。但是你可以利用 this

Until you find a proper selector, here is a small workaround, that selects elements with matching attribute

var nodes = [];
$("body > *").each(function(){ //iterating over all nodes
  $(this.attributes).each(function(){
    console.log(this.nodeName);
    if(this.nodeName.indexOf("data-abc") > -1){
      nodes.push(this);
    }
  });
});

console.log(nodes.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-abc-name="value">...</div>
<a href="..." data-abc-another="something">...</a>
<span data-nonabc="123">...</span>


是的,如果没有选择器可用,手动遍历DOM并检查属性是唯一的选择。然而,这非常低效。您的代码仅检查顶级元素。我需要在DOM中的任何地方找到元素。而且在我的情况下,DOM本身非常大(超过一百万个元素)。话虽如此,很可能这就是jQuery正在做的事情。 - Aleks G

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接