jquery - 尝试理解 jQuery nth-child

标签 jquery

我目前在理解 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 of n 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/

相关文章:

javascript - 页面加载后将 iframe 源加载到 Foundation Modal

javascript - 在动态位置生成下拉菜单

javascript - 单击我的菜单时,如何根据显示的菜单使两个无序列表淡入淡出?

javascript - 使用鼠标位置在网页上滚动 - 将鼠标悬停在侧面元素上

Javascript:在另一个函数中调用函数不起作用?

c# - 如何在.cs中的特定时间执行javascript?

jquery - 如何解析 Goodreads API 的 XML 响应?

javascript - 如何在数组 Javascript 中正确存储和格式化数据

javascript - 在 jQuery.each 外部声明的变量在 jQuery.each 主体中变为未定义

javascript - 使复选框磁贴可点击