For example, the following code
var box = document.getElementById("box");
box.onclick = function(){
console.log(111);
};
box = null;
Why can I still trigger the click event of the box when I assign the value of the box to null? What I think is that although the box is assigned to null later, since the event has been added, the processing of the event has nothing to do with the box itself? I don’t know if this is right. Why can I just assign box.onclick to null? Doesn’t onclick belong to the box? , I hope you guys can give me a reasonable answer, thank you.
phpcn_u15822017-05-19 10:35:15
The box here is just a variable
var box = document.getElementById("box");
Here is assigning the reference of the "box" element to the box. Your box = null
是把null
assigning the value to the box below has no effect on the "box" element. It is recommended to read this article
Maybe what I said is not very clear, please forgive me.
过去多啦不再A梦2017-05-19 10:35:15
var box = document.getElementById("box");//生成一个box指针, 指向element
box.onclick //element绑定点击事件
box = null; // 清空指针 与element无关
PHPz2017-05-19 10:35:15
You just gave the nickname "Xiao Ming" to another person, but the damage you caused to the original "Xiao Ming" is still there...
As an experienced driver, I must correct your whitewashing steps:
1 , first cover up your sins
box.onclick = null;
2. It depends on the situation whether you want to destroy the body or not
box = null;
或
box.parentNode.removeChild(box);
阿神2017-05-19 10:35:15
In fact, box is just a "pointer" to a DOM element.
Your operation on the box attribute will affect the DOM element, but when you assign it to null, you only change the pointing of the box, but it does not mean that the DOM element is cleared.