在 JavaScript 中,对象如何在发生事件时自毁?
我有这个功能,可以即时创建 DIV。 但现在,我想在 onclick 事件上销毁这个对象,但我只是不知道如何销毁。
function creatediv(id) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.onclick=function(){this=null;}; //bad function
document.body.appendChild(newdiv);
}
我缺少什么?
谢谢
I have this function, to create a DIV on-the-fly. But now, I want to destroy this object on onclick event, but I just don't know how.
function creatediv(id) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.onclick=function(){this=null;}; //bad function
document.body.appendChild(newdiv);
}
What am I missing?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅将其设置为 null 不会破坏它。 您需要将其从文档树中删除,同时确保没有引用指向它。
Just setting it null will not destroy it. You need to remove it from the document tree while making sure there are no references pointing to it.
接受的答案对我来说似乎是错误的。 首先,它不考虑 newdiv 包含子节点,因此建议的删除例程通过闭包(IE)保持内存泄漏的危险。 其次,由于 'newdiv = null' 的位置,creatediv 函数立即销毁刚刚创建的元素。
我建议对点击处理程序使用 Douglas Crockfords purge 函数,并用它替换 d 。
The accepted answer seems wrong to me. First, it doesn't consider newdiv containing childnodes, so the suggested remove routine maintains a danger for memory leaks via closures (IE). Second, because of the position of 'newdiv = null' the creatediv function immediately destroys the just created element.
I would recommend using Douglas Crockfords purge function for the click handler, substituting d with this.