组合 jQuery :not 和 :nth-child 选择器


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

我正在尝试选择没有特定类的每三项。这是我的jQuery选择器,但它不起作用 - 似乎第n个子选择器忽略了: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

谢谢! :)

我能看到完成这项工作的唯一方法是使用两个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 报告说,不出所料,单个过滤器有点快,但只是非常、非常、非常轻微。

引用:

  • filter() .
  • hasClass() .

改用该方法过滤结果怎么样?

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

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

最好的简单方法=)

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

祝你好运=)

更新:我认为这在第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/)

: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/​

第 N 个子级在使用组的过滤选择时可能违反直觉。

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

var count = 0;
$('.select-all-these:not(.except-these)').each(function(){
    if ( count++ % 2 == 0 ) $(this).css('color','red')
})

最新更新