简体   繁体   中英

If I bind a JavaScript event to an element, then delete the element, what happens to the event?

Let's say I have an element:

<section id="container">
    <div id="curious">hey, there</div>
</section>

Then, after the DOM loads, I bind an event to the element, like so:

$('#curious').click(function (){
  alert('Are you curious?');
});

Later on, the element gets deleted:

$('#container').html('');

What happens to the bound event? Is it deleted too? Does it linger around? Is it a good practice to clean it up?

According to the jQuery documentation for the .html() method , the event handlers are removed.

This is done to prevent memory leaks.

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

Similarly, the same applies when using the .empty() / .remove() methods as well:

all bound events and jQuery data associated with the elements are removed.

If you want to retain the data and event listeners, use the .detach() method instead. The .detach() method is essentially the same as the .remove() method except for the fact that it keeps all jQuery data associated with the removed elements (which means that you can append the same element after detaching it, and the events would still be bound).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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