操作innerHTML 删除子元素的事件处理程序? [英] Manipulating innerHTML removes the event handler of a child element?
本文介绍了操作innerHTML 删除子元素的事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个非常简单的演示:
I have this very simple demo:
function foo() {
alert('Works!');
}
var inp = document.createElement('input');
inp.onblur = foo;
document.body.appendChild(inp);
参见此处: http://jsfiddle.net/A7aPA/
如您所见,这是有效的.(点击输入,然后点击其他地方,会弹出一个警告.)
As you can see, this works. (Click on the input, then click somewhere else and an alert will pop up.)
但是,如果我将这一行添加到 JavaScript 代码中:
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).
见这里: http://jsfiddle.net/A7aPA/1/
这是为什么?
推荐答案
是的,当您这样做时:
document.body.innerHTML += '<br>';
你真的在做:
document.body.innerHTML = (document.body.innerHTML + '<br>');
因此,您完全破坏并重新创建了所有内容.
So you're completely destroying and recreating all the content.
这篇关于操作innerHTML 删除子元素的事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文