开发者

Manipulating innerHTML removes the event handler of a child element? [duplicate]

This question already has answers here: Is it possible to开发者_如何学JAVA append to innerHTML without destroying descendants' event listeners? (13 answers) Closed 7 years ago.

I have this very simple demo:

function foo() {
    alert('Works!');
}

var inp = document.createElement('input');
inp.onblur = foo;
document.body.appendChild(inp);

See here: http://jsfiddle.net/A7aPA/

As you can see, this works. (Click on the input, then click somewhere else and an alert will pop up.)

However, if I add this line to the JavaScript code:

document.body.innerHTML += '<br>'; 

then the blur handler stops working (and no error is thrown btw).

See here: http://jsfiddle.net/A7aPA/1/

Why is that?


Yes, when you do:

document.body.innerHTML += '<br>'; 

You're really doing:

document.body.innerHTML = (document.body.innerHTML + '<br>'); 

So you're completely destroying and recreating all the content.


Modifying innerHTML causes the content to be re-parsed and DOM nodes to be recreated, losing the handlers you have attached. Appending elements as in the first example doesn't cause that behavior, so no re-parsing has to occur, since you are modify the DOM tree explicitly.

Another good way to handle this is to use insertAdjacentHTML(). For example:

document.body.insertAdjacentHTML('beforeend', '<br>')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜