2013-04-06 112 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()相对于其同级的指数收益。

相关问题