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
?
最佳答案
why the output is
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);
});
关于jquery - 为什么 index() 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15853229/