我目前在理解 jQuery 中的第 n 个子选择器时遇到一些困难。
我有一个定义如下的列表:
<ul class="nopadding nomargin" role="tablist">
<li class="application inline" role="tab">
<li id="tabHome" class="inline active" role="tab">
<li id="tabSendReceive" class="inline" role="tab">
<li id="tabFolder" class="inline" role="tab">
<li id="tabView" class="inline" role="tab">
</ul>
您会注意到第一个 LI 元素具有应用程序类,而其他元素则没有。现在,我正在编写一个 API,它应该能够根据索引选择选项卡元素。
这是它的 jQuery 代码:
EnableTabIndex : function(tabIndex) {
console.log($("li[role=tab]:not(.application):nth-child(" + tabIndex + ")").attr("id"));
}
我只是在这里使用 console.log 进行测试。 据我对 jQuery 的了解,它应该采用匹配的第 n 个元素:
现在,由于某种奇怪的原因,当我作为 tabIndex 2 传递时,结果是 TabHome (第一个选项卡元素)。
我不明白为什么是第二个。
我可以理解0或1(取决于jQuery从0或1开始的值),但它不应该是2。
有人可以解释一下为什么会发生这种情况吗?
最佳答案
您想要.eq()
,不是.nth-child()
。为什么?因为作为 nth-child() docs状态,它们基于 CSS nth-child 规则,这些规则仅适用于元素,而不适用于元素的类:
Because jQuery's implementation of
:nth-
selectors is strictly derived from the CSS specification, the value ofn
is "1-indexed", meaning that the counting starts at 1. For other selector expressions such as:eq()
or:even
jQuery follows JavaScript's "0-indexed" counting. Given a single<ul>
containing two<li>
s, $( "li:nth-child(1)" ) selects the first<li>
while $( "li:eq(1)" ) selects the second.The
:nth-child(n)
pseudo-class is easily confused with:eq(n)
, even though the two can result in dramatically different matched elements. With:nth-child(n)
, all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With:eq(n)
only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the(n+1)th
one (n
is 0-based) is selected.
所以:
console.log($("li[role=tab]:not('.application'):eq(2)").attr("id"));
会给你tabFolder
,索引为二(从零开始)的元素,abs 位于角色和 :not
上您使用的过滤器。
关于jquery - 尝试理解 jQuery nth-child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24418418/