2

私は次のようないくつかのdivを持っています:

<div id="parent">
  <div class="child">
    <div class="gChild">
     <button></button> 
    </div>
    <div class="gChild">
     <button></button> 
    </div>
  </div>
  <div class="child">
    <div class="gChild">
     <button></button> 
    </div>
    <div class="gChild">
     <button></button> 
    </div>
  </div>
</div>

<div id="NextSet">
  <div class="child">
    <div class="gChild">
     <button></button> 
    </div>
    <div class="gChild">
     <button></button> 
    </div>
  </div>
</div>

クリックされたボタンから「子」のインデックスを取得したいと思います。これは最初のセット「#parent」で機能します

$(this).parents('.child').index();

しかし、2 番目のセット '#NextSet' にはありません。これは、#parent のすべての .child 要素がparents() にも追加されるためです。私は試した:

$(this).closest('.child').parent().index();

しかし、それは正しくありません...

4

1 に答える 1

2

closest()セレクターに一致する最初の親を見つけるため、次のようになります。

$(this).closest('.child').index()

parents()セレクターに一致するすべての親を検索します。

.childすべての要素内のインデックスを取得するには、コレクションを渡します。

$(this).closest('.child').index('.child');
于 2013-04-17T18:12:57.410 に答える