如何正确使用 jQuery 中的第 nth-child 单步执行一个类型的对象?

How to properly use nth-child in jQuery to step through objects of a type?

我 运行 遇到了一个奇怪的错误,它似乎特定于 jQuery 中的 nth-child selection 语法。我可以使用 $('list').each() 成功地单步执行下面 HTML 中的列表,但是当使用 nth-child selection 子句时,它似乎计算 <br />两个 list 块之间的标签。

对于HTML:

<list id="c" view="vw_project_content" where="`project` = %%2%%">
    <item>
        <b>$$title$$</b><br />
        $$message$$
        <br />
    </item>
</list>
<br />
Discussion:
<list id="p" view="vw_project_posts" where="`project` = %%2%%" limit="100">
    <item>
        <b>$$poster_id$$</b><br />
        $$message$$
        <br />
    </item>
</list>

以及以下代码:

console.log($('list:nth-child(1)'));
console.log($('list:nth-child(2)'));
console.log($('list:nth-child(3)'));

我收到输出:

[list#c, prevObject: jQuery.fn.init(1)]
[prevObject: jQuery.fn.init(1)]
[list#p, prevObject: jQuery.fn.init(1)]

但是,如果我删除两个 list 块之间的 <br />,它会生成:

[list#c, prevObject: jQuery.fn.init(1)]
[list#p, prevObject: jQuery.fn.init(1)]
[prevObject: jQuery.fn.init(1)]

是否有正确的方法来可靠地 select 特定类型的 nth-child,而不需要知道目标块之间存在什么?

您看到这些结果的原因是 nth-child() 选择器的工作方式。在您的示例代码中,当您尝试使用 $('list:nth-child(2)') 时,您告诉它要抓取的是一个 list 元素,它是它的父元素的第二个子元素。在您的 HTML list#c 中是其父项的第一个子项,而 list#p 是其父项的第三个子项。这就是为什么当存在 <br /> 标签时您收到 $('list:nth-child(2)') 的空响应。

如果您要做的是在一组 list 元素中获得特定位置,您可以尝试使用 eq() 选择器。例如:

注意:eq() 选择器是 0 索引而不是 1 索引。

console.log($('list:eq(0)'));
console.log($('list:eq(1)'));