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

前端 未结 13 1376
悲哀的现实
悲哀的现实 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:19

    I created my markup to insert as a string since it's less code and easier to read than working with the fancy dom stuff.

    Then I made it innerHTML of a temporary element just so I could take the one and only child of that element and attach to the body.

    var html = '
    '; html += 'Hello div!'; html += '
    '; var tempElement = document.createElement('div'); tempElement.innerHTML = html; document.getElementsByTagName('body')[0].appendChild(tempElement.firstChild);

提交回复
热议问题