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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:48:06  来源:igfitidea点击:

jQuery each: run through each set of a li individually

javascriptjqueryloopseach

提问by matt

I don't even know how to explain my problem - that's where the weird title comes from. I have a ulwrapping another ullike 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>
…

enter image description here

在此处输入图片说明

So each li.yearhas another <ul>with multiple children inside.

所以每个人li.year都有另一个<ul>里面有多个孩子。

Now my problem:

现在我的问题:

I wonder how I can run through eachli.yearindividually.

我想知道我如何才能eachli.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 eachloop runs through a ALL <li>s. I wonder how I can run through each li:year liindividually. Sounds weird right?

然而,这个each循环通过一个 ALL <li>s。我想知道我如何才能li:year li单独完成每个任务。听起来很奇怪吧?

So I actually want to loop through each of li.yearindividually so that my icount 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 ulseparately:

使用嵌套循环分别迭代每个内部的子级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');
});

回答by Alexander

Alternatively, you could also use .index().

或者,您也可以使用.index().

$('ul.event-items li.year ul li').each(function() {
  var $this = $(this);
  if ( $this.index() % 4 == 0 ) $this.addClass('clearLeft');
});

.index()will return you the index of each liin relation to its parent, ul.

.index()将返回每个li相对于其父级的索引,ul