gpt4 book ai didi

jquery - 如何为每 4-1 个元素添加一个类?

转载 作者:行者123 更新时间:2023-12-01 00:37:31 25 4
gpt4 key购买 nike

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

有人可以帮忙吗?

最佳答案

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

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

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

http://jsfiddle.net/AvPhe/ - 根据您的示例输入,zebra 类与文本“此处”一起添加。

关于jquery - 如何为每 4-1 个元素添加一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3068480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com