为什么 jquery nth child 在应用于 ul 和 li 时给出不一致的结果

Why jquery nth child give inconsistent result when apply to ul and li

我有一个包含一组 ul 的容器,每个容器有 4 个 li。 我创建了第一个 ul 然后通过 Javascript.

复制其余的

当我调用查找所有 ul 中的 nth-child 时,例如 $("ul:nth-child(1)"),它 return 什么都没有,第一个 ul 项出现 $("ul:nth-child(2)") (n从2开始)

但是当我尝试对 ul 中的 li 执行相同操作时,第一个 li 项目出现 $("ul li:nth-child(1)")(n 从 1 开始)

我在 jQuery 1.11.1 中开发,但是 fiddle 在使用 1.11.0 时给出了相同的结果(因为菜单中还没有 1.11.1)

我是不是遗漏了什么或者是 jQuery 中的错误?

参考: 在 Chrome 40.0.2214.93 m under Windows 7 Enterprise/English

下测试

这是example fiddle

已编辑:(更精确的愿望) 我并不是要查找 li,因为我知道如何准确地找到哪个 li 和带有“>”的 li,而我的意思是即使对 ul 元素和 li 元素使用相同的算法,它给出了不同的结果。

我想使用 nth-child 在所有 ul 中找到 (2n-1) ul,但它给出了错误的结果。我必须使用 (3n-1) 而不是每隔 3 个 ul 查找,因为起始元素比预期多 1 个。

(基于上面的例子,每3个ul元素检索一次)

start from first `ul` element amongst 15 `ul`s (skip every 3 ul element)
the first ul element in the set $(".keywords ul:nth-child(1)") 
give nothing (not as expected)
eg. $(".keywords ul:nth-child(3n-1)"), when n = 1, first element is 2, the starting element in the set is 2. 

为什么多了1个元素级联?

(仅使用第一个列表来测试检索每 3 个 li 元素)

$(".keywords ul:eq(0) li:nth-child(2n-1)")
the first li element in the set $(".keywords ul:eq(0) li:nth-child(1)") 
give the first element.(as expected) when n = 1, first element is 1, as expected.

因此,示例中指定的 ul 和 li 的跳过似乎有所不同。 虽然我仍然可以得到想要的结果,但当应用于 ul 时,它会级联 1 个元素。

您需要使用后代选择器

$(".main-area .list-container .keywords ul > li:nth-child(1)").length

演示:Fiddle

您的选择器试图找到 .main-area .list-container .keywords 内的 ul 并且是其父元素的第一个子元素。

ul:nth-childli:nth-child 的含义不同。在第一种情况下,您要查找的 ul 元素是其父元素的第 n 个子元素。在第二个中,您正在寻找列表中的第 n 个 li