Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 每3个元素添加一个类,并使用X类排除元素_Javascript_Jquery - Fatal编程技术网

Javascript 每3个元素添加一个类,并使用X类排除元素

Javascript 每3个元素添加一个类,并使用X类排除元素,javascript,jquery,Javascript,Jquery,我正在尝试编写一个函数,循环遍历我所有的元素,并在每3个元素(1、4、7、10等)中添加一个类,除非该元素具有类“foo” 在我的循环中,他们是这样做的吗 $('.container12 > .grid_12 > .grid_4').filter(function (index) { return index % 3 === 0; }).addClass("alpha"); 您可以使用选择器: $('.container12 > .grid_12 > .grid

我正在尝试编写一个函数,循环遍历我所有的元素,并在每3个元素(1、4、7、10等)中添加一个类,除非该元素具有类“foo”

在我的循环中,他们是这样做的吗

$('.container12 > .grid_12 > .grid_4').filter(function (index) { 
   return index % 3 === 0;
}).addClass("alpha");
您可以使用选择器:

$('.container12 > .grid_12 > .grid_4:nth-child(3n+1):not(\'.foo\')')
.addClass("alpha");
这个怎么样:

$('.container12 > .grid_12 > .grid_4').filter(function (index) { 
   return !$(this).hasClass('x') && index % 3 === 0;
}).addClass("alpha");

您可能正在查找
:not()
选择器:

试试这个:

$(".container12 > .grid_12 > .grid_4 li:not('.foo')")
    .filter(function (index) { 
       return index % 3 === 0;
    })
    .addClass("alpha");
它将
alpha
类应用于每三个元素,忽略类为
foo
的元素


要排除类,可以执行类似于
.addClass('alpha')。而不是('x')
@Krisholenbeck在添加类之前,您可能希望进行筛选,不是吗?是的,我只是给出了一个如何使用它的简单示例。这是最好的方法,在我看来,
n子项
选择器比
筛选
更简洁。