tags:

views:

39

answers:

3

Hello,

I'm dynamically inserting some html into the document (by using obj.innerHTML += 'some html'). In that html, there are images with 'imageId_X' ids (ie. imageId_1, imageId_2...). This works fine, but there's something wrong with the following code:

    for (var n = 0; n < pConfig.images.length; n++)
    {
        document.getElementById('imageId_' + n).onclick = function()
        {
            alert(n);
        }
    }

There are 4 elements in the pConfig.images and alert(n) always alerts 4. Why is this happening, what am i doing wrong?

+3  A: 

The cause of your problem is lamba expression in your code. When you define your anonymous function as onclick handler you bound it for outer variable n, which at the end of the loop is always 4 that the reason you get it always 4. To do it the way you have planned it to be you need to do the following:

for (var n = 0; n < pConfig.images.length; n++)
{
    function( n) {
      document.getElementById('imageId_' + n).onclick = function()
      {
        alert(n);
      }
    }( n);
}

Hence you define separate scope for variable.

Artem Barger
Thank you for your help
Marius S.
A: 

The problem is that each function you create has a reference to the same n variable - the one that is incremented. By the end of the loop, it is at 4 - and all functions you made refer to that variable with that value.

You can work around it with a closure, e.g.:

function closure(n) {
  return function() {alert(n);}
}

for (var n = 0; n < pConfig.images.length; n++)
{
    document.getElementById('imageId_' + n).onclick = closure(n);
}
sje397
Thank you, this works
Marius S.