为什么index()不按预期工作

HTML:

Div 1
Div 2
Div 3
Div 4
Test

Test

Test

Test

jQuery的:

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

小提琴演示

我希望结果是0, 1, 2, 3但为什么输出是4, 6, 8, 10

为什么输出是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); }); 

轻松修复 – .each支持索引:

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

你想要做的是:

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

.index()返回相对于其兄弟的索引。

index()给出了与其兄弟姐妹相关的元素索引 。 带有类文本的第一个div是第5个元素并且具有索引4,br是在5个索引处,而下一个div与类test具有索引6,依此类推。 我们可以通过以下演示检查每个元素的索引

现场演示

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

如果没有参数传递给.index()方法,则返回值是一个整数,指示jQuery对象中第一个元素相对于其兄弟元素Reference的位置 。

你必须相对于你正在测试的东西。 使用:

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

jsFiddle示例

根据.index()上的文档:

如果在元素集合上调用.index()并传入DOM元素或jQuery对象,则.index()返回一个整数,指示传递的元素相对于原​​始集合的位置。