开发者

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

Don't ask why but I need to add class zebra to the <li> elements with the content next to them. This is as far as I've got, but I'm not sure what calculation to use:

$("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&开发者_StackOverflowgt;
  <li></li>
  <li></li> <!-- add the zebra class here -->
  <li></li>
</ul>

Can anyone help?


The :nth-child() selector can accept an equation, and it solves your problem perfectly:

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

Selects every 4th li starting at 3 onwards, :nth-child(4n-1) would also work (every 4th-1 element). No each() or modulo necessary.

http://jsfiddle.net/AvPhe/ - Example based on your sample input, the zebra class is added along with the text "Here".


From what I can tell, you want the 3rd, 7th, 11th, ... with class "zebra":

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

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

});

EDIT: Check out Andy's answer. Much better than mine :-)


The period is 4 so the modulo should be 4.
However it is offset by two so you need to add 2 to the index:

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


if (index % 4 == 2)

is what I think you're looking for.

In your example, you have the 3rd, 7th and 10th elements selected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜