In jQuery, if you delete an element, will any events on it be deleted?

For example, if I have a link with the following event associated with it:

$("ad").bind("click", this, onDelete); 

And later do:

 $("ad").remove(); 

It's good? Or does it cause a memory leak and do I need to call unbind 1st?

Thanks for any help.

+4
source share
4 answers

I have not tested it, but I believe that deleting an element will cancel its event handlers. I came to this conclusion from the jQuery API documentation (search for deletion), which says that if you want to move an element from one part of the DOM to another, that:

 $("#foo").remove().appendTo("#bar"); 

should be written as

 $("#foo").appendTo("#bar"); 

to avoid losing event handlers.

+4
source

From jQuery docs to remove ()

Removes all matched elements from the DOM. This does NOT remove them from the jQuery object, allowing you to use consistent elements. Note that this function, starting with 1.2.2, will also delete all event handlers and internally cached data.

+6
source

The answer is yes, if the event was related to jQuery. If you attach something like "onclick", I do not believe it will be.

This article discusses some of them. It also defines a recursive function to remove all click events for an element and all its children. It will cover jQuery click handlers, as well as handlers defined with onclick so that you are covered.

http://www.computerhowtoguy.com/how-to-use-the-jquery-unbind-method-on-all-child-elements/

 function RecursiveUnbind($jElement) { // remove this element and all of its children click events $jElement.unbind(); $jElement.removeAttr('onclick'); $jElement.children().each(function () { RecursiveUnbind($(this)); }); } 

To use the function in the previous example, we will call a function that passes it a β€œcontainer” div as a jQuery object.

 RecursiveUnbind($('#container')); 
0
source

For writing, you do not need to worry about memory leak in javascript. (chill man, not C ++!)

The javascript browser engine manages all objects, and garbage collects them. When I say objects, this also means event handling functions, because functions are also objects in javascript.

Unrelated: I like how all objects in javascript: D

Hooray!
Jrh

-2
source

All Articles