简体   繁体   English

在javascript中,对象如何自我破坏事件?

[英]How can a object self destruct on an event, in javascript?

I have this function, to create a DIV on-the-fly. 我具有此功能,可以即时创建DIV。 But now, I want to destroy this object on onclick event, but I just don't know how. 但是现在,我想在onclick事件中销毁该对象,但是我只是不知道如何。

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 谢谢

Just setting it null will not destroy it. 仅将其设置为null不会破坏它。 You need to remove it from the document tree while making sure there are no references pointing to it. 您需要从文档树中删除它,同时确保没有指向它的引用。

function creatediv(id) {
    var newdiv = document.createElement('div');
    newdiv.setAttribute('id', id);
    newdiv.onclick=function(e) {
        this.parentNode.removeChild(this);
    };  
    document.body.appendChild(newdiv);
    newdiv = null;//required in IE to prevent memory leak
}

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). 首先,它不考虑newdiv包含子节点,因此建议的remove例程通过闭包(IE)维护了内存泄漏的危险。 Second, because of the position of 'newdiv = null' the creatediv function immediately destroys the just created element. 其次,由于'newdiv = null'的位置,creatediv函数立即破坏了刚创建的元素。 I would recommend using Douglas Crockfords purge function for the click handler, substituting d with this. 我建议将Douglas Crockfords 清除功能用于单击处理程序,并用d代替。

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}
function removeElement(divNum) {
  var d = document.getElementById('myDiv');
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM