search

Home  >  Q&A  >  body text

javascript - Why does an event trigger when assigning null to an object?

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.

滿天的星座滿天的星座2753 days ago583

reply all(4)I'll reply

  • phpcn_u1582

    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是把nullassigning 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.

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:35:15

    var box = document.getElementById("box");//生成一个box指针, 指向element
    box.onclick //element绑定点击事件
    box = null; // 清空指针 与element无关

    reply
    0
  • PHPz

    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);

    reply
    0
  • 阿神

    阿神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.

    reply
    0
  • Cancelreply