开发者

How do I assign sequential values over a jQuery collection?

I feel like a bonehead: I wa开发者_StackOverflownt to assign index=i to each LI I have selected, with i incrementing. It appears to assign them all at once though, and they all get index=1. Thoughts?

$("#window ul li").each(function(){
    var i = 1;
    $(this).attr("index", i);
    i++;
});


The callback function that you pass into each is given the zero-based index in the collection as the first argument.

$("#window ul li").each(function(i){
    $(this).attr("index", i+1);
});

So if you want your index to start with 1, add 1.


It's because each executes the lambda function for each element separately and in each call you set the i=1. You can declare and inicialize the i before calling each.

var i = 1;
$("#window ul li").each(function(){
    $(this).attr("index", i);
    i++;
});

Edit: But Mario's solution is much better.


var i = 1;
$("#window ul li").each(function(){
    $(this).attr("index", i);
    i++;
});

This should work as well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜