【问题标题】:jQuery selector for elements with attribute starting with string具有以字符串开头的属性的元素的 jQuery 选择器
【发布时间】:2017-05-26 21:51:20
【问题描述】:

我需要选择所有具有以给定前缀开头的属性的元素 - 注意我说的是属性名称,不是值。例如:

<div data-abc-name="value">...</div>
<a href="..." data-abc-another="something">...</a>
<span data-nonabc="123">...</span>

在上面的 HTML 中,我需要获取属性以data-abc- 开头的所有元素——即diva

我该怎么做?

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:
    Array.from(document.querySelector('element').attributes).filter(x=>x.name.startsWith('attr-starts-with'))
    

    【讨论】:

      【解决方案2】:

      你可以通过 ES6 做到这一点:

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

      Online demo (jsFiddle)

      【讨论】:

        【解决方案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');
        

        【讨论】:

        • 我最近不得不用这个。我在这里的某个地方找到了答案,但我刚刚找不到源。如果有人知道,请告诉我,我会向作者提供所有权!
        • 这看起来很有希望。所以,要找到所有这些元素,我会使用$('*:attrStartsWith("data-abc-")')
        【解决方案4】:

        我认为我们没有 jQuery 选择器和 regex。但是你可以使用this

        在找到合适的选择器之前,这里有一个小解决方法,它选择匹配 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 无论如何都在做的原因。
        猜你喜欢
        • 1970-01-01
        • 2011-04-07
        • 1970-01-01
        • 2012-08-08
        • 2016-03-25
        • 2013-09-28
        • 2011-05-09
        • 2013-02-03
        • 1970-01-01
        相关资源
        最近更新 更多