如何为每个第4个-1个元素添加一个类? [英] How can I add a class to every 4th - 1 element?

查看:117
本文介绍了如何为每个第4个-1个元素添加一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不要问为什么,但我需要将斑马类添加到<li>元素中,并在其旁边添加内容.据我所知,但是我不确定要使用什么计算方法:

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>

任何人都可以帮忙吗?

推荐答案

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

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

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

从3开始选择每4个li:nth-child(4n-1)也将起作用(每个4th-1元素).无需each()或取模.

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/-基于示例输入的示例 zebra 类与文本"Here" 一起添加.

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

这篇关于如何为每个第4个-1个元素添加一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆