更新:我认为这对于 nth-child 或其他 jQuery 选择器是不可能的。所以考虑使用更详细的解决方案:
var count = 0;
$('.select-all-these').each(function() {
if(!$(this).hasClass('except-these')) {
count++;
}
if(count === 3) {
$(this).text('every 3rd element');
count = 0
}
});
http://jsfiddle.net/TJdFS/2/(替代版本:http: //jsfiddle.net/TJdFS/)
:nth-child 计算所有匹配元素,忽略任何附加过滤器,如 :not。
请参阅 jquery 文档:
:nth-child(n) 伪类很容易与 :eq(n) 混淆,尽管两者会导致匹配的元素截然不同。使用 :nth-child(n),所有子元素都被计算在内,无论它们是什么,并且仅当指定的元素与附加到伪类的选择器匹配时才会被选中。使用 :eq(n) 仅计算附加到伪类的选择器,不限于任何其他元素的子元素,并且选择第 (n+1) 个(n 从 0 开始)。
例子:
<div class="select-all-these">1</div>
<div class="select-all-these except-these">2</div>
<div class="select-all-these except-these">3</div>
<div class="select-all-these">4</div>
<div class="select-all-these except-these">5</div>
<div class="select-all-these">6</div>
JS:
$('.select-all-these:not(.except-these):nth-child(6)').text('nth-child counts all elements (1 based!)');
$('.select-all-these:not(.except-these):eq(1)').text('eq counts only matching elements (0 based!)');
结果:
1
2
3
eq counts only matching elements. (0 based!)
5
nth-child counts all elements (1 based!)
http://jsfiddle.net/nFtkE/2/
</p>