3

Could you please have a quick look at the sample code

http://jsfiddle.net/vXvs2/

I don't know if its clear, but what it's supposed to do is show what i was when the event was created. Instead what I think it's doing is showing the value of i when the event is fired.

How would I solve my issue?

Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
  • Possible duplicate of [Setting onclick to use current value of variable in loop](http://stackoverflow.com/questions/6048561/setting-onclick-to-use-current-value-of-variable-in-loop) and a few million others – Esailija Nov 24 '11 at 20:58

1 Answers1

6

Wrap the loop's body in a function, to create a closure:

for(var i = 0; i < arr.length; i++){
    (function(i){ //i inside this function is a local var; not affected by i++
        arr[i].onclick = function(){
            alert(i);
            return false;
        };
    })(i); //Invoke the function, pass variable i 
}

Fiddle: http://jsfiddle.net/vXvs2/4/

Rob W
  • 341,306
  • 83
  • 791
  • 678