开发者

jQuery .each() function. Resetting the index?

开发者 https://www.devze.com 2022-12-26 05:03 出处:网络
I have multiple lists with the same class. I\'d like to loop each list and its LI\'s and prepend the current number before each. The current code I have is:

I have multiple lists with the same class.

I'd like to loop each list and its LI's and prepend the current number before each. The current code I have is:

$jQuery(".numberList li").each(function(i) {

    var index = i + 1;

    $jQuery(this).prepend("<span>" + index + "</span>");

});

The problem is, is that the index doesn't restart back at 0 for each list it goes through, it just keeps going up. For e开发者_运维技巧xample, the output I get now is:

First list
1. item
2. item
3. item

Second list
4. item
5. item
6. item

Second list should start at 1 again by having the index back at 0.

Could someone point out where I'm going wrong? I'm not a jQuery expert or anything...clearly :)

Many thanks, Michael.


I'd think about nesting loops.

Something like:

$('.numberList').each(function(){
   $this.children('li').each(function(i){
      var index = i + 1;
      $jQuery(this).prepend("<span>" + index + "</span>");
   });
});


Why not use just stylesheets?

.numberList {
    list-style-type: decimal;
}

You can apply this style through jQuery if for some reason it has to be done dynamically:

$(".numberList").css("list-style-type", "decimal");​

An example here.

0

精彩评论

暂无评论...
验证码 换一张
取 消