简体   繁体   中英

Attaching event to multiple elements by Javascript

I'm trying to add a event to multiple elements, right now I have this code, it works, but I don't want to add a SetTimeout. If I take it away, it does not work.

Do you know why this is happening? Is there a better solution to this?

setTimeout(function () {
    var imageElements = document.querySelectorAll("img[class^='image']");
    for (var i = 0; i < imageElements.length; i++) {
        imageElements[i].addEventListener("click" , function(){
            definition(this.classList[0], this);
        })
    }
},200);

Because you're trying to add the event handler to an element which is not yet created or ready in DOM.

Use the following, Your code should be inside myFunction()

window.addEventListener('load', myFunction, false )

For older versions of IE, it uses:

document.attachEvent("onreadystatechange", myFunction);
//or
window.attachEvent("onload", myFunction);

Using some ES6 arrow functions and forEach

let imageElements = document.querySelectorAll("img[class^='image']");

imageElements.forEach(image => image.addEventListener('click', function(){ 
    definition(this.classList[0], this); 
});

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