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?
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.: