javascript jQuery each:单独运行每组 li
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13790754/
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
jQuery each: run through each set of a li individually
提问by matt
I don't even know how to explain my problem - that's where the weird title comes from.
I have a ul
wrapping another ul
like the sample underneath.
我什至不知道如何解释我的问题——这就是奇怪的标题的来源。我有一个像下面的样品一样的ul
包装ul
。
<ul class="event-items">
<li class="year 2012"></li>
<li class="year 2011"></li>
<li class="year 2010">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li class="year 2010"></li>
…
So each li.year
has another <ul>
with multiple children inside.
所以每个人li.year
都有另一个<ul>
里面有多个孩子。
Now my problem:
现在我的问题:
I wonder how I can run through each
li.year
individually.
我想知道我如何才能each
li.year
单独完成。
Right now I'm doing this …
现在我正在做这个……
$('ul.event-items li.year ul li').each(function(i) {
if ( i % 4 == 0 ) $(this).addClass('clearLeft');
});
However this each
loop runs through a ALL <li>
s. I wonder how I can run through each li:year li
individually. Sounds weird right?
然而,这个each
循环通过一个 ALL <li>
s。我想知道我如何才能li:year li
单独完成每个任务。听起来很奇怪吧?
So I actually want to loop through each of li.year
individually so that my i
count always starts fresh inside each li.year
所以我实际上想li.year
单独遍历每个,以便我的i
计数总是在每个内部重新开始li.year
回答by Asad Saeeduddin
Use nested loops to iterate over the children of each inner ul
separately:
使用嵌套循环分别迭代每个内部的子级ul
:
$('ul.event-items li.year ul').each(function() {
$("li", this).each(function(i) {
if (i % 4 == 0)
$(this).addClass('clearLeft');
});
});
回答by sroes
Is this what you mean?
你是这个意思吗?
$('ul.event-items li.year').each(function(i) {
if ( i % 4 == 0 ) $(this).find('ul li').addClass('clearLeft');
});