admin管理员组

文章数量:1414945

I'm using JQuery to set the HTML inside a div. Something like this:

$(div).html(strHtmlBlob);

strHtmlBlob is a chunk of HTML returned via Ajax from the server. After, it's assigned, I set up some events for elements in the new HTML blob by doing this:

$(div).find("a").click(a_ClickHandler);

That all works perfectly fine. The problem is REMOVING the events. I want to make sure I clean up the DOM properly.

I'm removing the HTML like so:

$(div).html("");

But I can see that the events are still there. Is there a way to clean up events for elements that no longer exist?

I'm using JQuery to set the HTML inside a div. Something like this:

$(div).html(strHtmlBlob);

strHtmlBlob is a chunk of HTML returned via Ajax from the server. After, it's assigned, I set up some events for elements in the new HTML blob by doing this:

$(div).find("a").click(a_ClickHandler);

That all works perfectly fine. The problem is REMOVING the events. I want to make sure I clean up the DOM properly.

I'm removing the HTML like so:

$(div).html("");

But I can see that the events are still there. Is there a way to clean up events for elements that no longer exist?

Share Improve this question asked Feb 18, 2009 at 20:37 Kenny SmithKenny Smith
Add a ment  | 

2 Answers 2

Reset to default 6

Use .remove() instead of .html("")

That will clear the elements and events all at once. JQuery does a lot of cleanup magic under the covers if you let it.

$(div).find('a').unbind('click');

Check out the documentation.

Alternatively, you should empty() it:

$(div).empty();

According to the docs:

Note that this function starting with 1.2.2 will also remove all event handlers and internally cached data.

本文标签: javascriptDoes JQuery have a way to unbind events in random HTML stringStack Overflow