Attach event to dynamic elements in javascript

前端 未结 10 2277
一生所求
一生所求 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:26

    The difference is in how you create and append elements in the DOM.

    If you create an element via document.createElement, add an event listener, and append it to the DOM. Your events will fire.

    If you create an element as a string like this: html += "

  • test
  • "`, the elment is technically just a string. Strings cannot have event listeners.

    One solution is to create each element with document.createElement and then add those to a DOM element directly.

    // Sample
    let li = document.createElement('li')
    document.querySelector('ul').appendChild(li)
    

提交回复
热议问题