结合jQuery:not和:nth-​​child选择器

Luk*_*bis 4 jquery jquery-selectors

$j('.select-all-these:not(.except-these):nth-child(3n)');
Run Code Online (Sandbox Code Playgroud)

我正在尝试选择没有特定课程的每三个项目.这是我的jQuery选择器,但它不起作用 - 似乎:nth-​​child选择器忽略:not选择器.我做错了吗?

作为一个例子,这是它应该如何工作:

.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
Run Code Online (Sandbox Code Playgroud)

谢谢!:)

kin*_*uta 6

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

$('.select-all-these:nth-child(3n)').not('.except-these');
Run Code Online (Sandbox Code Playgroud)

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


Dav*_*mas 5

我能看到做这项工作的唯一方法是使用两个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');
Run Code Online (Sandbox Code Playgroud)

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');
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

JS逆足报告说,单过滤器,勿庸置疑,快一点,但只是非常,非常,非常轻微.

参考文献: