2010-04-11 80 views
1

我有多个相同类的列表。jQuery .each()函数。重置索引?

我想循环每个列表及其LI,并在每个之前加上当前数字。当前的代码我已经是:

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

    var index = i + 1; 

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

}); 

的问题是,是该指数不会为每次经过,它只是不断上升名单在0重新回来。例如,输出我现在得到的是:

First list 
1. item 
2. item 
3. item 

Second list 
4. item 
5. item 
6. item 

其次名单应在1再次具有指标回到0

有人能指出我要去哪里错了启动?我不是一个jQuery专家或任何...明确:)

非常感谢, 迈克尔。

+0

重复:http://stackoverflow.com/questions/2615758/using-each-method-how-do-i-get-the-indexes-of-multiple-ordered-lists-to-each – interjay 2010-04-11 23:19:11

+0

感谢链接。我确实有过搜索,但无法想出正确的术语来获得好的结果。干杯。 – Michael 2010-04-11 23:23:29

回答

3

我会考虑嵌套循环。

喜欢的东西:

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

为什么不使用只是样式?

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

您可以通过jQuery的应用这种风格如果由于某种原因,它必须动态地进行:

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

example here

+0

这是更好的恕我直言。 – Raja 2010-04-11 23:45:20