Combining jQuery :not and :nth-child selectors

前端 未结 5 748
礼貌的吻别
礼貌的吻别 2021-01-19 06:56
$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 m

5条回答
  •  迷失自我
    2021-01-19 07:18

    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 Fiddle demo.

    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 Fiddle demo.

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

    References:

    • filter().
    • hasClass().

提交回复
热议问题