javascript 操作innerHTML 删除子元素的事件处理程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5113105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manipulating innerHTML removes the event handler of a child element?
提问by ?ime Vidas
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/
见这里: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:
但是,如果我将此行添加到 JavaScript 代码中:
document.body.innerHTML += '<br>';
then the blur handler stops working (and no error is thrown btw).
然后模糊处理程序停止工作(顺便说一句,没有抛出错误)。
See here:http://jsfiddle.net/A7aPA/1/
见这里:http : //jsfiddle.net/A7aPA/1/
Why is that?
这是为什么?
回答by user113716
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.
因此,您完全破坏并重新创建了所有内容。
回答by ctcherry
Modifying innerHTMLcauses 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.
修改innerHTML会导致重新解析内容并重新创建 DOM 节点,从而丢失您附加的处理程序。在第一个示例中添加元素不会导致该行为,因此不必重新解析,因为您显式修改了 DOM 树。
Another good way to handle this is to use insertAdjacentHTML(). For example:
处理此问题的另一个好方法是使用insertAdjacentHTML()。例如:
document.body.insertAdjacentHTML('beforeend', '<br>')

