Kinopiko
2009-11-14 16:36:13
+1
A:
Create a closure via a self-executing function literal (or a named factory function)
function doTask(x) { alert(x); }
for(var i = 100; i--;) {
document.getElementById('divNum' + i).onclick = (function(i) {
return function() { doTask(i); };
})(i);
}
or use the DOM node for information storage
function doTask() { alert(this.x); }
for(var i = 100; i--;) {
var node = document.getElementById('divNum' + i);
node.x = i;
node.onclick = doTask;
}
The latter is more memory-friendly as no superfluous function objects are created.
Christoph
2009-11-14 16:48:32
+2
A:
Although the (correct) answer is already given, I'd like to point out a more advanced method - replacing loops with iterators, which effectively solves javascript "late-bound" closures problem.
loop = function(start, end, step, body) {
for(var i = start; i != end; i += step)
body(i)
}
loop(1, 100, 1, function(i) {
// your binding stuff
})
stereofrog
2009-11-14 18:46:30