Do events handlers on a DOM node get deleted with the node?

后端 未结 5 679
死守一世寂寞
死守一世寂寞 2020-12-01 06:22

(Note: I\'m using jQuery below, but the question is really a general Javascript one.)

Say I\'ve got a div#formsection whose contents are repeatedly upda

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 06:55

    Not necessarily

    The documentation on jQuery's empty() method both answers my question and gives me a solution to my problem. It says:

    To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

    So: 1) if we didn't do this explicitly, we'd get memory leaks, and 2) by using empty(), I can avoid this.

    Therefore, I should do this:

    formSection.empty();
    formSection.html(newContents);
    

    It's still not clear to me whether .html() would take care of this by itself, but one extra line to be sure doesn't bother me.

提交回复
热议问题