jQuery nth-child混乱

时间:2013-06-12 01:50:13

标签: jquery-selectors

在此页面上: https://weargustin.com/store?filter=all

为什么这个选择器的第一个元素是:

$('div.funded.product:nth-child(3n)')

的第二个要素
$('div.funded.product')

?!

2 个答案:

答案 0 :(得分:3)

问题是nth-child循环遍历所有子节点并针对选择器测试它们。它不使用选择器然后循环匹配的那些。因此,正如PSL所提到的,你拥有的其他兄弟姐妹的东西正在抛弃整个事物。

这是一个分解它的例子:http://jsfiddle.net/Ga5Jq/

<div>
        <p>test</p>
        <span>1</span>
        <span>2</span>
        <span>3</span>
</div>


$(function() {
    alert($("div span:nth-child(3n)").html());
});

以上代码提醒2,因为第二个范围实际上是匹配选择器div的{​​{1}}的第三个孩子。

答案 1 :(得分:2)

我认为你想要选择该类型中的每一个,所以你应该尝试使用nth-of-type而不是nth-child,因为除了div.funded.product之外还有许多其他兄弟姐妹要开始使用.product.funding。例如,你有div $('div.funded.product:nth-of-type(3n+1)') 也作为同一父母的孩子进入。

{{1}}

请参阅:nth-of-type