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?

1

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

:) Perfect, I've been looking for this for ages. +1
Additionally, you can also pass arr[i], in case the DOM node gets modified. jsfiddle.net/vXvs2/5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.