Ash Burlaczenko
Ash Burlaczenko

Reputation: 25475

JavaScript - How to add onclick event dynamically passing in a specific value?

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?

Upvotes: 3

Views: 3319

Answers (1)

Rob W
Rob W

Reputation: 349262

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/

Upvotes: 6

Related Questions