views:

30

answers:

3

I'm thinking there's some basic stuff that I'm missing here;

for (var i=1; i<=5; i++) {
  var o = $('#asd'+i);

  o.mouseover(function() {
    console.info(i);
  });
}

When hovering over the five different elements, I always get out the last value from iteration; the value 5. What I want is different values depending of which element I'm hovering, all from 1 to 5.

What am I doing wrong here?

+2  A: 

You need a closure, as all of the mouseover functions are referencing the same variable whose value is changing:

for (var i=1; i<=5; i++) {
    (function(j) {
        $('#asd'+j).mouseover(function() {
            console.info(j);
        });
    })(i);
}

By creating a closure, the variable j is inside the local scope of the function and will not change when the "outer" i changes.

Tatu Ulmanen
There was indeed some basic stuff I was missing :-) Thanks a bunch!
ptrn
A: 

You need to wrap your function calls in more closures:

Refer to this : https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Closures#Creating_closures_in_loops.3a_A_common_mistake

I think this should work:

for (var i=1; i<=5; i++) {
  var o = $('#asd'+i);
  (function(j){
    o.mouseover(function(){
      console.info(j);
    });
  })(i);
}
Rajat
A: 

In this case i is bound inside a closure on each iteration, meaning that all the functions added to the objects points to the same variable, and since this variable was incremented on each iteration all functions refer to the last incremented value.

The way to avoid this is by copying the value to a new variable inside the closure

for (var i=1; i<=5; i++) {
     var o = $('#asd'+i);
    (function(newi) {
        o.mouseover(function() {
            console.info(newi);
        });
    }(i);
}
Sean Kinsey