2016-09-26 3 views
1

の特定のインデックスを取得します。親が異なる場合、どのように各パラグのインデックスを取得するには?私はこのようなものを試しました:私は、コードを次している要素

$('.same').each(function() { console.log($(this).index() }); 

しかし明らかに、それは各要素に対して同じ値を返しました。

答えて

2
$('.same').each(function(index) { console.log(index }); 
1

はとにかくeach反復と同じインデックスを返すもちろんの.index()

$('.same').each(function() { 
    console.log($(this).index('.same')); 
}); 

、用セレクタとして同じクラスを使用することができますが、それはあなたがに基づいてインデックスを返す方法ですindex()を使用して収集し、親要素のドキュメントから

に基づいて要素だけではなく、インデックス

.INDEX(セレクタ)

要素を探しにjQueryのコレクションを表すセレクタ。

他の方法は、周りにもeach機能はインデックスパラメータが付属しています

$('.same').index(this) 
2

動作します。

$(".same").each(function(i) { 
    console.log("index " + i); 
}); 

全スニペット:

$(".same").each(function(i) { 
 
    console.log("Item " + i); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 

 
<div class="something"> 
 
    <p class="same"> blah </p> <!-- should return index 0 --> 
 
</div> 
 

 
<div class="something-else"> 
 
    <p class="same"> blah </p> <!-- should return index 1 --> 
 
</div> 
 

 
<div class="other" > 
 
    <p class="same"> blah </p> <!-- should return index 2 --> 
 
</div>

0

あなたは本当に近くにあります。あなたの関数の中で、これは、同じ要素を持つ現在の要素のコンテキストを保持します。あなたは「同じ」クラスを持つ要素のリスト全体にそれを比較したいので

$('.same').each(function() { console.log($('.same').index(this))) 
0

.index()は親の内部のインデックスを返します。これらの段落のそれぞれが<div>を含む最初の要素であるため、たびに0が得られます。

$('.same').each(function() { 
 
    console.log($(this).parent().index()) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div class="something"> 
 
    <p class="same">blah</p> 
 
    <!-- should return index 0 --> 
 
    </div> 
 

 
    <div class="something-else"> 
 
    <p class="same">blah</p> 
 
    <!-- should return index 1 --> 
 
    </div> 
 

 
    <div class="other"> 
 
    <p class="same">blah</p> 
 
    <!-- should return index 2 --> 
 
    </div> 
 
</div>

0

これは動作します:

$('.same').each(function(index) {console.log(index)}); 
代わりに、あなたは親のインデックスを得ることができます
関連する問題