UPDATE: 我不认为这是可能的第n个孩子或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/)
:第n个孩子计算所有匹配的元素忽略任何额外的过滤器,如:没有。
见jQuery的文档:
的:第n个孩子(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/
我有一个类似的问题,而是想要做其他所有元素。因此,如果您只是在寻找其他所有元素而不是第三个元素,那么这是一种更简洁的方法。 '('。'select:not(.dontselect)')。filter(:even).css('color','red');' –