Closures in a for loop
closures, javascript, jquery, loops
Solution
See the bind method.
$('#button'+i).bind('click', {button: i}, function(event) {
foo(event.data.button);
});
From the docs:
The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures
Problem
Closures in a loop are causing me problems. I think I have to make another function that returns a function to solve the problem, but I can't get it to work with my jQuery code. Here is the basic problem in a simplified form: ``` function foo(val) { alert(val); } for (var i = 0; i < 3; i++) { $('#button'+i).click(function(){ foo(i); }); } ``` Naturally clicking on any of the three buttons will give an alert saying 3. The functionality I want is that clicking on button 1 will give an alert saying 1, button 2 will say 2 etc. How can I make it do that?