2016-09-26 160 views
1

的具體指標我有以下代碼:獲取元素

<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> 

我的問題很簡單。當父母不同時,如何獲得每個paragphs的索引?我試過這樣的:

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

但是,顯然它爲每個元素返回相同的值。

回答

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

您可以使用相同的類作爲選擇爲.index()

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

,那反正返回相同的指數作爲each迭代,但這是你如何返回基於一個索引收集使用index(),並根據父元素

從文檔上的元素不只是指數

的.index(選擇器)

表示一個jQuery集合,其中尋找一個 元件的選擇器。

其他的方式也適用

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

each功能配備了一個索引參數。

$(".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)});