Attach event to dynamic elements in javascript

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

    You must attach the event after insert elements, like that you don't attach a global event on your document but a specific event on the inserted elements.

    e.g.

    document.getElementById('form').addEventListener('submit', function(e) {
      e.preventDefault();
      var name = document.getElementById('txtName').value;
      var idElement = 'btnPrepend';
      var html = `
        
    • ${name}
    `; /* Insert the html into your DOM */ insertHTML('form', html); /* Add an event listener after insert html */ addEvent(idElement); }); const insertHTML = (tag = 'form', html, position = 'afterend', index = 0) => { document.getElementsByTagName(tag)[index].insertAdjacentHTML(position, html); } const addEvent = (id, event = 'click') => { document.getElementById(id).addEventListener(event, function() { insertHTML('ul', '
  • Prepending data
  • ', 'afterbegin') }); }

提交回复
热议问题