开发者

jQuery .each() function. Resetting the index?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜