For循环jQuery,在4个项目后重新开始

For loop jQuery, start over after 4 items

本文关键字:项目 重新开始 4个 循环 jQuery For      更新时间:2023-09-26

我有点纠结jquery中的for循环。我在类.row中有一个div。在这个div中有许多.itemdiv。我事先不知道项目的数量。

我想要的是在0开始计数,并在3结束。(0, 1, 2, 3, 0, 1, 2, 3等)

HTML:

<div class="row cl">
    <div class="item"></div>
</div>

我试过了:

$('.row > .item').each(function(i){
    for(i=0;i<4;++i){
       // Here i want to add a class (repeatedly) if the index of the .item is 3.
    }
});

上面示例中的结果不能正常工作。到处都是3。我知道如何添加一个类,这是关于计数部分。

我通常可以使用一个CSS选择器,如:nth-child(),但我需要它在ie8中工作,并且不支持所有的子选择器。

这些答案有很多错误

$('.row > .item').each(function(i){
   if (i % 4 == 3)
      // Add class.
      $(this).addClass("newclass");
});

晚安

您只需将i值与4值进行比较:

$('.row > .item').each(function(i){
   if (i % 3 == 0 && i != 0)
      // Add class.
      $(this).addClass("newclass");
});

或者也可以使用jQuery的:

$('.row .item:nth-child(3n)').addClass("active");

就像这样比较索引:

$('.row > .item').each(function( i,el ){
      if (i == 3)
          $(el).addClass("newclass");
});

据我所知,您想要在div下添加一个类'item'和'row'。

可以使用下面的代码片段:

$('.row > .item').each(function(i, ele){
    if((i+1) %4 ===0)
    //Add class using $(ele).addClass();
});

此外,您可以使用CSS3伪选择器(n -child)进行相同的操作。如果您需要解决方案的帮助,请告诉我。

问题是您正在使用for循环重置迭代器。这样做:

$('.row > .item').each(function(i){
    if (i % 3 == 0 && i != 0) {
       // Here i want to add a class if the index of the .item is 3.
    }
});

如果你想给每个索引为3的倍数的项添加一个类,你可以使用像

这样的余数运算符
$('.row .item').each(function(i){
   if (i % 3 == 0 && i != 0)
      $(this).addClass("you-new-class");
});