簡體   English   中英

如何在jQuery中選擇所有具有匹配屬性的元素?

[英]how to select all elements with matching attribute of this in jQuery?

我想使用this選擇器選擇div中與所選元素具有相同屬性的所有元素。

因此,在我的示例中,當我單擊帶有.foo類的元素時,我想在.container中查找與被單擊的元素共享相同data-index屬性的所有元素,然后添加.bah類。 目前,我只將函數.bah添加到單擊的元素上,我了解如何選擇某些屬性,但不選擇與this選擇器相關的屬性。

使用Javascript:

$(document).on('click','.foo', function() {
        $(this).addClass('bah');
});

HTML:

<div class="container">
  <div class="inner1">
    <div data-index="0" class="foo">
      <p>item 1</p>
    </div>
    <div data-index="2" class="foo">
      <p>item 2</p>
    </div>
  </div>
  <div class="inner2">
    <div data-index="0" class="foo">
      <p>item 1</p>
    </div>
    <div data-index="2" class="foo">
      <p>item 2</p>
    </div>
  </div>
</div>
$(document).on('click','.foo', function() {
    var dataIndex = $(this).data('index');
    $(document).find("div[data-index='" + dataIndex + "']").each(function() {
        $(this).addClass('bah');
    });
});

小提琴示例: http : //jsfiddle.net/9huw0ym9/1/

您可以使用.filter()獲得結果。

$(document).on('click','.foo', function() {
    var dataIndex = $(this).data('index');
    $('.container div').filter(function(){
        return $(this).data('index') === dataIndex
    }).addClass('bah');
});

或使用基於屬性的選擇器。

$(document).on('click','.foo', function() {
    var dataIndex = $(this).data('index');
    $('.container div[data-index="'+dataIndex+'"]').addClass('bah');
}); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM