为什么index()不能按预期工作
问题描述:
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);
});
我希望结果是0, 1, 2, 3
,但是为什么输出是4, 6, 8, 10
?
I would expect the result is 0, 1, 2, 3
but why the output is 4, 6, 8, 10
?
答
为什么输出为
4, 6, 8, 10
$(this).index()
返回元素相对于其兄弟姐妹的索引,而不是相对于所选元素的索引. br
和.divX
元素也是同级!
$(this).index()
returns the index of the element relative to its siblings, not to the selected elements. The br
and .divX
elements are siblings as well!
看起来像您想要的:
var $tests = $(".test");
$tests.each(function(){
var i = $tests.index(this);
alert(i);
});
或更简单:
$(".test").each(function(i){
alert(i);
});