Is it possible to append to innerHTML without destroying descendants' event listeners?

前端 未结 13 1198
悲哀的现实
悲哀的现实 2020-11-21 23:40

In the following example code, I attach an onclick event handler to the span containing the text \"foo\". The handler is an anonymous function that pops up an <

13条回答
  •  一个人的身影
    2020-11-22 00:27

    Using .insertAdjacentHTML() preserves event listeners, and is supported by all major browsers. It's a simple one-line replacement for .innerHTML.

    var html_to_insert = "

    New paragraph

    "; // with .innerHTML, destroys event listeners document.getElementById('mydiv').innerHTML += html_to_insert; // with .insertAdjacentHTML, preserves event listeners document.getElementById('mydiv').insertAdjacentHTML('beforeend', html_to_insert);

    The 'beforeend' argument specifies where in the element to insert the HTML content. Options are 'beforebegin', 'afterbegin', 'beforeend', and 'afterend'. Their corresponding locations are:

    
    

    Existing content in #mydiv

提交回复
热议问题