为什么index()不能按预期工作 [英] Why doesn't index() working as expected

查看:85
本文介绍了为什么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);
});

这篇关于为什么index()不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆