3

不要问为什么,但我需要将类斑马添加到<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>

任何人都可以帮忙吗?

4

4 回答 4

12

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

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

li从 3 开始,每 4 选择一次,:nth-child(4n-1)也可以工作(每 4-1 个元素)。不需要each()或模数。

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

于 2010-06-18T09:32:23.530 回答
2

据我所知,你想要第 3、第 7、第 11、... 类“斑马”:

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

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

});

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

于 2010-06-18T09:27:07.613 回答
0

周期为 4,因此模数应为 4。
但是它偏移了 2,因此您需要将 2 添加到索引:

if ((index + 2) % 4 == 0)
于 2010-06-18T09:25:51.617 回答
0
if (index % 4 == 2)

是我认为你正在寻找的。

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

于 2010-06-18T09:27:13.337 回答