jQuery 每 n 个 addClass
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1260277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
addClass every nth
提问by davebowker
I have a list of elements that I want to style in 3 different ways.
我有一个元素列表,我想以 3 种不同的方式进行样式设置。
I want every 3rd list item to have the same class throughout the whole list.
我希望每个第三个列表项在整个列表中都具有相同的类。
For example:
例如:
<li class="A">Some Content</li>
<li class="B">Some Content</li>
<li class="C">Some Content</li>
<li class="A">Some Content</li>
<li class="B">Some Content</li>
<li class="C">Some Content</li>
<li class="A">Some Content</li>
<li class="B">Some Content</li>
<li class="C">Some Content</li>
I can do 2 with :odd/even, but how to do it with 3?
我可以用 :odd/even 做 2,但是如何用 3 做呢?
回答by Marc
try
尝试
$("ul li:nth-child(3n+1)").addClass("A")
$("ul li:nth-child(3n+2)").addClass("B")
$("ul li:nth-child(3n)").addClass("C")
Feel free to consolidate it to make it prettier, but I wanted to expose the selectors.
随意合并它以使其更漂亮,但我想公开选择器。
回答by VoteyDisciple
I recommend something like this:
我推荐这样的东西:
var i = 0;
$("li").each(function() {
var newClass = 'A';
if (i % 3 == 1) newClass = 'B';
if (i % 3 == 2) newClass = 'C';
$(this).addClass(newClass);
});