操纵innerHTML会删除子元素的事件处理程序? [英] Manipulating innerHTML removes the event handler of a child element?
本文介绍了操纵innerHTML会删除子元素的事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个非常简单的演示:
function foo(){
alert('Works!') ;
}
var inp = document.createElement('input');
inp.onblur = foo;
document.body.appendChild(inp);
请参阅这里: http://jsfiddle.net/A7aPA/
正如你所看到的,这有效。 (点击输入,然后点击别的地方,弹出一个警告。)
但是,如果我将这行添加到JavaScript代码中:
document.body.innerHTML + ='< br>';
然后模糊处理程序停止工作(并且没有错误被抛出btw)。
请参阅这里: http ://jsfiddle.net/A7aPA/1/
为什么这样?
是的,当你这样做:
document.body.innerHTML + ='< br> ;';
你真的在做:
document.body.innerHTML =(document.body.innerHTML +'< br>');
所以你完全摧毁并重新创建所有内容。
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.
这篇关于操纵innerHTML会删除子元素的事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文