0

Possible Duplicate:
Javascript: closure of loop?

Pseudo javascript:

for (i, i<10, i++) {
  new element.addEvent('click', function(){ alert(i) }).inject(dom)
}

When the loop finishes all the onclick events will trigger alerts with the 'final' value of i. What is the 'correct' way of having them alert the value of i as it was when the onclick event was added?

When I say correct I mean that I'm aware there are several ways of achiving this behavior, but I want to know the standard (ie expected by people that may encounter the code) way. Thanks.

2
  • 7
    candidate for most often asked question... Commented Jun 19, 2012 at 7:43
  • @FlorianMargaine There are yet 4 closing votes. Commented Jun 19, 2012 at 7:45

1 Answer 1

3

Use a closure to capture the value of i at each iteration:

for (i; i<10; i++) {
    (function(i) {
         new element.addEvent('click', function(){ alert(i) }).inject(dom);
    }(i));
}
Sign up to request clarification or add additional context in comments.

9 Comments

Why the downvote? While it's not valid JavaScript it does answer the question in the same pseudocode-way the OP used.
I downvoted because he could have closed to vote instead of answering this. Avoiding SO pollution, etc.
@FlorianMargaine - Look at the list of people who closed. I am one of them. While it is a duplicate, I feel it can still be helpful to a new SO user to receive a direct answer.
Alright. Removed the downvote :)
While we're here, we might as well use the correct for syntax. (what are those commas doing?)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.