I have an problem with the code below that's related to closures, that I need some help with.
As you can see I am creating several images in the for-loop that i'm assigning different id's (ie. the numbers from the array). So far, so good. When I click on the different images I want the function showId to be called with the images id's as argument, but the problem is that the number that's used as an argument to the function always becomes nr 8 (the last number in the array). How can I solve this?
Thanks in advance.
var imageArea = document.getElementById('imageArea');
var nrArray = [1,2,3,4,5,6,7,8];
for (var i = 0; i < nrArray.length; i++){
var image = document.createElement('img');
image.src = "images/theimage.png";
image.id = nrArray[i];
imgArea.appendChild(image);
image.addEventListener ('click',function() {showId(image.id);},false);
}