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

爷,独闯天下 提交于 2019-12-10 10:18:23

问题


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>
  <li></li>
  <li></li> <!-- add the zebra class here -->
  <li></li>
</ul>

Can anyone help?


回答1:


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".




回答2:


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 :-)




回答3:


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)



回答4:


if (index % 4 == 2)

is what I think you're looking for.

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



来源:https://stackoverflow.com/questions/3068480/how-can-i-add-a-class-to-every-4th-1-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!