Marius S.
Marius S.

Reputation: 559

weird javascript problem

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?

Upvotes: 0

Views: 70

Answers (3)

Daniel Lee
Daniel Lee

Reputation: 7969

Looks like you need a closure. See How do JavaScript closures work?

Upvotes: 0

Artem Barger
Artem Barger

Reputation: 41222

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.

Upvotes: 3

sje397
sje397

Reputation: 41812

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);
}

Upvotes: 0

Related Questions