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

chc*_*ist 3 jquery modulo

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

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

    }
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

And*_*y E 12

:nth-child()选择可以接受的公式,它完美地解决您的问题:

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

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

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