代码之家  ›  专栏  ›  技术社区  ›  aalaap

如何使用jquery只匹配具有特定属性而没有其他属性的元素?

  •  1
  • aalaap  · 技术社区  · 6 年前

    假设示例元素:

    <a href="..." rel="...">...
    <a href="..." rel="..." target="...">...
    

    如何只匹配第一个元素?我想告诉jquery只匹配 <a> 具有 href 以及 rel 属性,但没有其他属性。 :not() 需要我提到要排除的特定属性,但是未知属性呢?

    4 回复  |  直到 6 年前
        1
  •  4
  •   charlietfl    6 年前

    使用filter()并检查属性长度。注意,添加类或数据属性意味着您需要修改

    $('a[href][rel]').filter(function(){
       return this.attributes.length === 2;  
    }).css('color','red')
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" rel="foo" target="_blank"> Has target</a>
    <a href="#" rel="foo" > No target</a>
    <a href="#"  > No rel </a>
        2
  •  1
  •   totallyNotLizards    6 年前

    你可以使用 not() first() 函数的作用是,选择集合中的第一个元素并筛选出不需要的元素。

    例子:

    $("a[href][rel]").not("[target]").first();
    

    为了排除包含其他未知属性的项,应该使用filter作为其他答案的建议。

    不过,这不是一个好的解决方案,最好将类添加到需要选择的元素中,或者将它们放在另一个div中。

        3
  •  0
  •   Satpal    6 年前

    使用 .filter() 用测试条件来检查元素只有属性长度

    $('a[href][rel]').filter(function() {
      return this.attributes.length == 2
    }).addClass('a');
    .a {
      background-color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="..." rel="...">...</a>
    <a href="..." rel="..." target="...">...</a>
        4
  •  0
  •   Ankit Agarwal    6 年前

    你可以用 this.hasAttribute 再进一步检查 this.attributes.length === 2 以确认 <a> 元素只有两个属性:

    $('a').each(function(){
       if(this.attributes.length == 2 && this.hasAttribute("href") && this.hasAttribute("rel")){
         $(this).addClass('selected');
       }
    });
    .selected{
      color: green;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="..." rel="...">1111</a>
    <a href="..." rel="..." target="...">222</a>
    <a href="..." rel="...">333</a>
    <a href="..." rel="..." target="...">444</a>