Setting onclick to use current value of variable in loop [duplicate]

Try the following

b.onclick= function(arg) {
    return function() {
        alert(arg);
    }
}(a);

The problem you were hitting is that javascript doesn’t use block scope. Instead all variables have a lifetime of their containing function. So there was only ever one a captured in all of the onclick functions and they all see it’s final value.

The solution works around this by creating a new function and value per scope and then immediately setting that value to the current value of a.

Here’s a version that’s a bit expanded and perhaps a bit more readable

var createClickHandler = function(arg) {
  return function() { alert(arg); };
}

for(var a=0;a<10;a++) {
    var b=document.createElement('b')
    b.onclick = createClickHandler(a);
    b.innerHTML=a
    document.body.appendChild(b)
}

Leave a Comment