如何为每个第4个

编程入门 行业动态 更新时间:2024-10-15 14:16:48
本文介绍了如何为每个第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.

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

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

更多推荐

如何为每个第4个

本文发布于:2023-10-23 05:19:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519901.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:何为

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!