![](/img/trans.png)
[英]Javascript add event listener in a foreach loop only last entry works
[英]Vanilla Javascript: .forEach Loop Not Applying Event Listener
尋找有關為什么此循環未將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); } )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.