Sorry if the title isn't exactly accurate, not sure how else to describe it. I have this bit of js I pieced together using various other tutorials. It's working, but I was hoping for a little more understanding on how/why it works.
The code is for a modal on a page full of images, where you click on any image and it launches a modal with that image in it. Here are the relevant parts of the code:
function modal(modalId, modalImg) {
var image = document.getElementsByClassName('modalImg');
var imageLength = image.length;
var myModal = document.getElementById(modalId);
var modalImg = document.getElementById(modalImg);
for (var i = 0; i < imageLength; i++) {
(function(index) {
image[i].onclick = function() {
myModal.style.display = "block";
modalImg.src = this.src;
imgIndex = index;
}
})(i);
}
}
You can see this code working (and in full context) here .
The part I'm trying to understand here involves the closure function and event listener. So the closure function is being called, and i
(the for-loop's counter) is passed as the index
argument. My question is, how the heck is i
being set to the index of the image that was clicked?
If we look at this code snippet:
(function(index) {
image[i].onclick = function() {
myModal.style.display = "block";
modalImg.src = this.src;
// `index` here is a variable accessible through closure scope
imgIndex = index;
}
})(i);
The code iterates over all images and passes each image index as i
variable, which is then captured as closure
inside click
callback.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.