简体   繁体   中英

How to apply add_event_listener() on newly created element?

I am using this script to apply add_event_listener() when the DOM is already loaded.

document.addEventListener("DOMContentLoaded",regFunct,false);

then I list all the function inside regFunct function. all the function inside the regFunct which is loaded from the server are working except the newly created element using appendChild() .

function regFunct(){
    //doSomething1
    //doSomething2 (create new HTML element)

    //doSomething3 (apply add_event_listener() after
    //              the new element created by doSomething2)
}

doSomething3 is not working.

For elements that are created only after the DOMContentLoaded event already fired, you can create a delegate listener .

Here's one possible approach. Let's assume you want to listen to the click event on a dynamically added button that has the id myNewButton :

 document.addEventListener('DOMContentLoaded', function(event) { // lets create and add the button only when DOMContentLoaded has already fired let btn = document.createElement('button'); btn.id = "myNewButton"; btn.type = "button"; btn.textContent = "My shiny new button"; document.getElementById('app').appendChild(btn); }) // before the above is executed, let's add a delegate click listener document.addEventListener('click', function(event) { if (event.target.id === 'myNewButton') { event.target.textContent += " was clicked!"; } }) 
 <div id="app"></div> 

Please note that this only works for events that bubble . Examples of events that don't bubble by default: scroll , blur , focus .

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