操纵的innerHTML删除一个子元素的事件处理程序? [英] Manipulating innerHTML removes the event handler of a child element?

查看:270
本文介绍了操纵的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的code:

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

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

那么模糊处理程序停止工作(并没有错误BTW抛出)。

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

在这里看到: http://jsfiddle.net/A7aPA/1/

这是为什么?

推荐答案

是的,当你这样做:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆