简体   繁体   中英

Vanilla Javascript: .forEach Loop Not Applying Event Listener

Looking for some support on why this loop is not applying the eventlisteners to the 2 image elements.

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();

The problem is that after you set up the click handlers, you overwrite the document.body.innerHTML with new HTML elements and wipe out the elements that you just set up.

Instead, inject that new HTML into a portion of the document, but not the 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>

The assignments inside the forEach() will not change the original array elements (ie videoThumbnails) as they operate on a copy of the array elements, and not the array elements themselves:

 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); } )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM