5
$j('.select-all-these:not(.except-these):nth-child(3n)');

I'm trying to select every third item that doesn't have a particular class. This is my jQuery selector, but it doesn't work - it seems that the :nth-child selector ignores the :not selector. Am I doing it wrong?

As an example, this is how it should work:

.select-all-these.except-these
.select-all-these.except-these
.select-all-these.except-these
.select-all-these
.select-all-these.except-these
.select-all-these
.select-all-these <-- THIS ONE IS SELECTED
.select-all-these.except-these

Thanks! :)

4

5 回答 5

6

如何使用该方法来过滤结果呢?

$('.select-all-these:nth-child(3n)').not('.except-these');

这是一个要演示的小提琴:http: //jsfiddle.net/ntNgC/

于 2012-05-09T05:18:00.650 回答
6

我能看到完成这项工作的唯一方法是使用两个filter()调用:

$('.select').filter(
    function(){
        return !$(this).hasClass('dontselect');
    }).filter(
        function(i){
            return (i+1)%3 == 0; // unless you want a zero-based count, regular CSS is one-based
        }).css('color','red');

JS 小提琴演示

但是,您可以使用filter()带有外部变量的单个调用:

var count = 0;
$('.select').filter(
    function(){
        console.log(!$(this).hasClass('dontselect'));
        if (!$(this).hasClass('dontselect')){
            count++;
            return count%3 == 0;
        }
    }).css('color','red');

JS 小提琴演示

JS Perf 报告说,毫无疑问,单个过滤器要快一点,但只是非常、非常非常边缘。

参考:

于 2012-05-09T06:31:10.277 回答
3

更新:我认为这对于 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>

于 2012-05-09T05:22:24.820 回答
3

最简单的方法=)

$('table tr:not(.class)').eq(1);

祝你好运=)

于 2014-01-13T18:29:42.493 回答
1

Nth-child 在处理组的过滤选择时可能会违反直觉。

使用 .each() 来绕过它的限制:

var count = 0;
$('.select-all-these:not(.except-these)').each(function(){
    if ( count++ % 2 == 0 ) $(this).css('color','red')
})
于 2012-10-26T04:52:49.290 回答