3

Possible Duplicate:
Passing values to onclick

I have 100 elements with ids divNum0,...,divNum99. Each when clicked should call doTask with the right parameter.

The code below unfortunately does not close i, and hence doTask is called with 100 for all the elements.

function doTask(x) {alert(x);}

for (var i=0; i<100; ++i) {
    document.getElementById('divNum'+i).addEventListener('click',function() {doTask(i);},false);
}

Is there someway I can make the function called with right parameters?

Community
  • 1
  • 1
KalEl
  • 8,978
  • 13
  • 47
  • 56
  • if you don't need to add more than one event listener, you should assign to `onclick` as this works across browsers – Christoph Nov 14 '09 at 16:52
  • I'd also suggest considering to use event delegation and put the click handler just to the parent element. When the click event fires, you just check the target and execute the wanted functionality. – Kimmo Puputti Nov 14 '09 at 18:54

2 Answers2

3

Although the (correct) answer is the duplicate, 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
})
Community
  • 1
  • 1
user187291
  • 53,363
  • 19
  • 95
  • 127
2

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
  • 164,997
  • 36
  • 182
  • 240
  • NB: it's more accurate to say [immediately-invoked function expression](https://en.m.wikipedia.org/wiki/Immediately-invoked_function_expression) :) – Braden Best Jan 18 '17 at 09:48