Attach event to dynamic elements in javascript

前端 未结 10 2425
一生所求
一生所求 2020-11-21 23:16

I\'m trying to insert html data dynamically to a list that is dynamically created, but when i try to attach an onclick event for the button that is dynamically created the e

10条回答
  •  庸人自扰
    2020-11-21 23:41

    You can do something similar to this:

    // Get the parent to attatch the element into
    var parent = document.getElementsByTagName("ul")[0];
    
    // Create element with random id
    var element = document.createElement("li");
    element.id = "li-"+Math.floor(Math.random()*9999);
    
    // Add event listener
    element.addEventListener("click", EVENT_FN);
    
    // Add to parent
    parent.appendChild(element);
    

提交回复
热议问题