A tip for event function within a loop, function closure

By | February 5, 2011

When I was writing some javascript at work a while ago, I encountered a problem, see below:

for (var i=0; i<10; i++){
  $('#element'+i).click(function(){
    alert(i);
  });
}

When I click the element, it always returned 9, because the event function is not included into the context until it is triggered, therefore, while the click function is triggered, the variable “i” is already 9 (after the loop).

Put it a simple way, this is how the program executes:
1. from 1 to 9, register the following click code to the elements (element0, element1, element2)
2. the click code will alert the value of variable i, sure it’s 9, after step 1.

But, what I really wanted was:
1. from 1 to 9, register the following click code to the elements (element0, element1, element2)
2. the click code will alert whatever the value of variable i during the register

here is the solution, to make the value of i persistent to the event, this technique is called closure

for (var i=0; i<10; i++){
  $('#element'+i).click(function(){
    createClosure(i);
  });
}

function createClosure(value){
  return function(){alert(value)};
}

Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.