HTML:
<ul>
<li class="selected">First Item</li>
<li class="disabled">Second Item</li>
<li class="separator">Third Item</li>
<li>Fourth Item</li>
</ul>
jQuery:
alert($("li:not(.disabled,.separator)").index());
根据 the documentation对于索引:
the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
强调第一个元素
。但是上面的代码返回 3
。根据文档,这段代码不应该返回 0
吗?
您可以在此处查看实际效果:http://jsfiddle.net/Zf9Vv/
注意:
我的选择器匹配两个元素:第一个和最后一个 LI
。
最佳答案
编辑(见评论) 原始答案不正确...我暂时将其保留在这里,以便评论有意义。
查看 index
的 jQuery 源代码, 你可以看到 following snippet :
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
将此与早期版本 1.6.2 中的相应(如果非常不同)片段进行比较。注意 this[0]
的使用:
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );
似乎在当前版本中 this.prevAll
部分导致问题。如果将其更改为 this.eq(0).prevAll
(它复制了 index
文档中的内容)然后您将获得正确的返回值。所以看起来这是一个 jQuery 错误。
在1.6.2版本中,inArray
用来。该方法返回第二个参数中第一个参数的索引(如果在第二个参数中找不到第一个参数,则返回 -1
)。因为第一个参数是 this[0]
(匹配集中的第一个元素)我们得到了预期的结果。
这是一个 updated fiddle包含修改后的 jQuery 源代码。提示正确的结果。
原始答案(这是不正确的):
再次仔细阅读文档中引用的部分(添加了粗体突出显示):
the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
仅仅因为两个 sibling 已从匹配集中移除,它不会更改 index
返回的值.换句话说,匹配元素 ( <li>Fourth Item</li>
) 相对于其兄弟元素的索引始终为 3(当然,除非在相关元素之前将新的兄弟元素插入到 DOM 中)。
关于javascript - 为什么这个 jQuery 返回索引 3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8424575/