我正在为jquery中的for循环而挣扎。我有一个.row类的div。在这个div里面有一些.item div,我不知道预先的项目数。
我想要的是在开始计数,在3结束。喜欢(0,1,2,3,0,1,2,3...etc)
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块。我知道如何添加一个类--这都是关于计数部分的。
我通常可以使用像
:nth-child()这样的CSS选择器,但是我需要它在IE8中工作,而这并不支持所有的子选择器。
发布于 2015-10-07 11:59:00
这些答案中有很多是错误的
$('.row > .item').each(function(i){
if (i % 4 == 3)
// Add class.
$(this).addClass("newclass");
});晚安
发布于 2015-10-07 11:47:05
您只需要比较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");发布于 2015-10-07 11:49:09
问题是您正在用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.
}
});https://stackoverflow.com/questions/32991335
复制相似问题