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);
}
There are a bazillion answers to this exact same question here on stackoverflow, i'll hunt some down in a minute, but here are the key points:
functionvar image = ... isn't where you think it is. There is only one image variable, which (due to lexical scoping) is the variable you are accessing in your closure, which at the conclusion of the loop will obviously point at the last iterated item.So for example:
(function(localImage) {
image.addEventListener ('click',function() {showId(localImage.id);},false);
})(image);
Also, as others have pointed out, event listener closures are executed in the context that they were bound. So conversely, without having worry about using a close to fix a scope, you could do:
image.addEventListener ('click',function() {showId(this.id);},false);
Edit
Some links to similar questions and some different perspectives on the answer:
I could go on but a bazillion is a big number...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With