结合jQuery:not和:nth-​​child选择器 [英] Combining jQuery :not and :nth-child selectors

查看:91
本文介绍了结合jQuery:not和:nth-​​child选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

谢谢! :)

推荐答案

我能看到的唯一方法是使用两个filter()调用:

The only way I could see to make this work was to use two filter() calls:

$('.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()调用,并使用一个外部变量:

You could, though, use a single filter() call, with an external variable:

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报告说,单个过滤器快一点点就不足为奇了 ,但仅非常 非常 非常有限.

JS Perf reports that the single filter is, unsurprisingly, a little faster, but only very, very, very marginally.

参考文献:

这篇关于结合jQuery:not和:nth-​​child选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆