2013-04-06 46 views
2

HTML:爲什麼不能按預期工作指數()

<div class="div1">Div 1</div> 
<div class="div2">Div 2</div> 
<div class="div3">Div 3</div> 
<div class="div4">Div 4</div> 

<div class="test">Test</div> 
<br /> 
<div class="test">Test</div> 
<br /> 
<div class="test">Test</div> 
<br /> 
<div class="test">Test</div> 
<br /> 

的Jquery:

$(".test").each(function(){ 
    var i = $(this).index(); 
    alert(i); 
}); 

Fiddle Demo

我希望結果是0, 1, 2, 3但爲什麼輸出是4, 6, 8, 10

回答

3

爲什麼輸出元件相對於4, 6, 8, 10

$(this).index()返回索引到其兄弟姐妹,而不是所選擇的元素。 br.divX元素也是兄弟姐妹!

它看起來像你想:

var $tests = $(".test"); 

$tests.each(function(){ 
    var i = $tests.index(this); 
    alert(i); 
}); 

或簡單:

$(".test").each(function(i){ 
    alert(i); 
}); 
3

易於修復 - 。每個支持指數:

$(".test").each(function(idx){ 
    alert(idx); 
}); 
3

指數()給出元素的索引相對於它的兄弟姐妹。帶類文本的第一個div是第5個元素,索引爲4,br爲5索引,下一個div爲class test,索引爲6等等。如果沒有參數被傳遞給所述的.index()方法我們可以通過下面的演示

Live Demo

$("#parent1 *").each(function() { 
    alert("TagName >> " + this.tagName + ", Index >> " + $(this).index() + ", Text " + $(this).text()); 
}); 

檢查每個元素的索引,返回值是 的整數指示第一個元素在 jQuery對象中相對於其同級元素的位置,Reference

2

你必須使它相對於你對測試的內容。用途:

$(".test").each(function(){ 
    var i = $('.test').index($(this)); 
    console.log(i); 
}); 

jsFiddle example

%的文檔上.index()

如果的.index()調用元素的集合,DOM元素或 jQuery對象傳遞in,.index()返回一個整數,指示傳入元素相對於原​​始集合的位置。

3

你想要做的是什麼:

$(".test").each(function(i) { 
    alert(i); 
}); 

.index()相對於其同級的指數收益。

相關問題