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');' –