I have 3 .a and a function that is supposed to alert the number [0, 1 or 2] .a belongs to when it is mouseover-ed:
function a(){
for(var c=0; c<3; c++){
alert(c);
$('.a:eq('+c+')').mouseover(function(){alert(c)});
}
}
When I execute it, the first alert(c) is triggered three times and the message is “0”, “1” ,”2″ respectively, as expected.
However, when mouseover .a, no matter which .a it is, it alerts “3”.
I would appreciate if someone can explain why this is happening and provide a solution.
This is happening because each of your
mouseoverfunctions are using the same value ofc, which is3when the loop is done.You need to make a closue to “capture” the value of
cfor each iteration.DEMO: http://jsfiddle.net/vDbu3/