Vanilla Javascript:.forEach循环未应用事件侦听器



正在寻找一些关于此循环为什么不将eventlisteners应用于2个图像元素的支持。

HTML:

<img src="video-embed.jpg" alt="text content">
<img src="video-embed-copy.jpg" alt="text content">

JAVASCRIPT:

let videoThumbnails = document.querySelectorAll('img[src*="video-embed"]');

function toggleGalleryModal(modal) {
console.log(clicked);
document.getElementById(modal).classList.toggle("show-modal");
}

function buildGalleryModals() {

videoThumbnails.forEach(function (thumbnail, index) {
let modalID = 'vid-gallery-modal-' + index,
altText = thumbnail.alt;

thumbnail.addEventListener('click', function (event) {
console.log('thumbnail[i]: ' + index);
});

document.body.innerHTML += '<div id="' + modalID + '" class="vid-gallery-modal"><div class="modal-content"><span class="close-button">×</span>' + altText + '</div></div>';
});
}

buildGalleryModals();

问题是,在设置点击处理程序后,您会用新的HTML元素覆盖document.body.innerHTML,并清除刚刚设置的元素。

相反,将新的HTML注入文档的一部分,而不是document.body

let videoThumbnails = document.querySelectorAll('img[src*="video-embed"]');
function toggleGalleryModal(modal) {
console.log(clicked);
document.getElementById(modal).classList.toggle("show-modal");
}
function buildGalleryModals() {
videoThumbnails.forEach(function (thumbnail, index) {
let modalID = 'vid-gallery-modal-' + index, 
altText = thumbnail.alt;
thumbnail.addEventListener('click', function (event) {
console.log('thumbnail[i]: ' + index);
});
document.getElementById("output").innerHTML += '<div id="' + modalID + '" class="vid-gallery-modal"><div class="modal-content"><span class="close-button">×</span>' + altText + '</div></div>';
});
}
buildGalleryModals();
<img src="video-embed.jpg" alt="text content1">
<img src="video-embed-copy.jpg" alt="text content2">
<div id="output"></div>

forEach((内部的赋值不会改变原始数组元素(即videoThumbnails(,因为它们对数组元素的副本进行操作,而不会改变数组元素本身:

myArray = [1,2,3,4,5]
// try to assign new value to array elements using forEach
myArray.forEach(e => {
e = '0';
console.log(e);
}
)
// see that elements in original array are unchanged
myArray.forEach(e => {
console.log(e);
}
)

最新更新