4

我有 6 个元素,我想每隔第二个和第三个元素过滤一次,所以我想要元素 2、3、5 和 6。我已经尝试过.filter(':nth-child(2n+1)'));,但显然过滤了 2、4 和 6。

我尝试的另一种方法是删除元素 1 和 4,但我找不到与过滤器相反的 jQuery 函数,它可以从集合中删除元素。

4

5 回答 5

4
.filter(':not(:nth-child(1),:nth-child(4))')

http://jsbin.com/owosuw/2/edit#source

于 2012-04-09T19:22:49.457 回答
3

以您的示例为例,我认为您实际上并不想要 2n 和 3n。您想要每组 3 个中的第 2 个和第 3 个吗?然后其中任何一个都应该起作用:

.filter(':nth-child(3n+2), :nth-child(3n+3)'));
.filter(':not(:nth-child(3n+1))');
于 2012-04-09T19:32:02.067 回答
2

您还可以使用filter一个函数(它接受一个参数,它是匹配元素的从零开始的数字):

$('div').filter( function(n) { return n%3!=0 } )

在此处查看我的 JSFiddle 概念验证:

http://jsfiddle.net/4c4Re/

于 2012-04-09T19:39:30.537 回答
1

I think you can't do it with only one nth-child. I don't know what you want to do, but if you want to give it a style or class or event or something in that category you can give it them all and remove it from the 1th and the 4th:

$('div').addClass('red');

$('div:nth-child(3n+1)').removeClass('red');

Live example: http://jsfiddle.net/gnbMH/


You could also use two nth-childs to get it work:

$('div:nth-child(3n+2)').addClass('red');
$('div:nth-child(3n+3)').addClass('red');

Live example: http://jsfiddle.net/gnbMH/1/


You also could combine to the two nth-childs and then you get something like this:

var elems = $('div:nth-child(3n+2)');
$('div:nth-child(3n+3)').each(function(i,elem) {
    elems.push(elem);
});

$(elems).addClass('red');

Live example: http://jsfiddle.net/gnbMH/2/

于 2012-04-09T19:24:40.907 回答
0

尝试使用:not(:nth-child(3n+1)).. 类似的东西.filter(':not(:nth-child(3n+1))').

演示

于 2012-04-09T19:31:31.637 回答