views:

35

answers:

3

I feel like a bonehead: I want 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++;
});
+4  A: 

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.

Mario Menger
Wow; so it takes care of the iterator for you... Who knew. Thanks!
Alex Mcp
A: 

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.

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

This should work as well.

Marc