我发誓我以前已经这样做过,但我正在尝试计算 div 中的前 5 个项目,然后向它们添加一个类,然后向其余的添加一个类。
我有这个:
var counter = 0;
$('.images img').each(function(i) {
if (i == 0) {
counter = 0;
} else {
counter++;
}
if (counter < 5) {
$(this).addClass('this');
} else {
$(this).addClass('other');
}
});
这有效,但我觉得它可以清理一下。有什么建议可以让它变得更精简吗?
最佳答案
要达到预期结果,请使用以下选项
- 使用 .each 循环 div
- 检查索引并添加Class
- 在第 5 个元素后使用 return false 退出循环
$('div').each(function(index) {
if(index < 5){
$(this).addClass('mark')
}else {
return false;
}
})
.mark{
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>1</div>
<div>1</div>
关于javascript - 使用 jQuery 将 Class 添加到 div 中的前 5 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56193369/