最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery each: run through each set of a li individually - Stack Overflow

programmeradmin0浏览0评论

I don't even know how to explain my problem - that's where the weird title es from. I have a ul wrapping another ul like the sample underneath.

<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.

Now my problem:

I wonder how I can run through each li.year individually.

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?

So I actually want to loop through each of li.year individually so that my i count always starts fresh inside each li.year

I don't even know how to explain my problem - that's where the weird title es from. I have a ul wrapping another ul like the sample underneath.

<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.

Now my problem:

I wonder how I can run through each li.year individually.

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?

So I actually want to loop through each of li.year individually so that my i count always starts fresh inside each li.year

Share Improve this question asked Dec 9, 2012 at 19:10 mattmatt 44.4k107 gold badges268 silver badges402 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Use nested loops to iterate over the children of each inner ul separately:

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

Is this what you mean?

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

Alternatively, you could also use .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 li in relation to its parent, ul.

发布评论

评论列表(0)

  1. 暂无评论