繁体   English   中英

如何为每个第4个元素添加一个类?

[英]How can I add a class to every 4th - 1 element?

不要问为什么,但我需要将类斑马添加到<li>元素及其旁边的内容。 这是我所拥有的,但我不确定使用什么计算:

$("li").each(function(index){
    if(index % ??? == 0) {  // <-- not sure what to put here

    }
});
<ul>
  <li></li>
  <li></li>
  <li></li> <!-- add the zebra class here -->
  <li></li>
  <li></li>
  <li></li>
  <li></li> <!-- add the zebra class here -->
  <li></li>
  <li></li>
  <li></li>
  <li></li> <!-- add the zebra class here -->
  <li></li>
</ul>

有人可以帮忙吗?

:nth-child()选择器可以接受一个等式,它完美地解决了你的问题:

$('ul li:nth-child(4n+3)').addClass("zebra").text("Here");

从3开始选择每4个li:nth-child(4n-1)也可以工作(每4-1个元素)。 没有必要的each()或模数。

http://jsfiddle.net/AvPhe/ - 基于您的示例输入的示例, zebra类与文本“Here”一起添加。

从我所知道的,你想要第3,第7,第11,...类“斑马”:

$("li").each(function(index,item){

if((index+2)%4 == 0) {
  $(item).addClass("zebra");
}

});

编辑 :查看安迪的答案。 比我好多了:-)

期间为4,因此模数应为4。
但是它被两个偏移,所以你需要在索引中加2:

if ((index + 2) % 4 == 0)
if (index % 4 == 2)

是我认为你正在寻找的。

在您的示例中,您选择了第3个,第7个和第10个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM