On Jul 25, 3:17 am, Karl Rudd wrote: > The "i" in the click function (closure) is just a reference > to the "i" outside. That "i" changes with each iteration of > the for loop. > > If you want to save a copy of the value of "i" then create > a _local_ var _inside_ the closure and assign it the > value of "i". > > For example: > > for (var i = 1; i < totalPages + 1; i++) { > $("#pages_panel").append($("<span> " + i + "</span>") > .click(function() { var saved = i; pageClicked(saved); > console.log("i:" + saved); })); > > }
How is that going to help? Executing - saved = i - inside the function is still going to reference the - i - variable from the containing scope, and so assign whatever value it has at the time of assignment, which will still be after the containing loop has finished and so after - i - has been assigned a value greater than - totalPages -. A more viable approach (though far from efficient as it creates two function object for each iteration of the loop) would be to replace the inner function with the inline execution of a function expression that returned the inner function, passing in the current value of - i - as an argument to the function call, and allowing the returned function to reference the value at that point via the outer function's formal parameter. I.E.:- for (var i = 1; i < totalPages + 1; i++) { $("#pages_panel").append($("<span> " + i + "</span>") .click( (function(x){ return (function(){ pageClicked(x); console.log("i:" + x); }); })(i) ) ); } > Closures are tricky constructions till you get used to them. Yes, but understanding is worth more than familiarity. <URL: http://jibbering.com/faq/faq_notes/closures.html >