Do I need to detach events in jQuery when I remove elements

白昼怎懂夜的黑 提交于 2019-12-01 13:59:04

问题


I have a UI using dynamic tabs, so content can be loaded into a tab and then the tab can be closed and the content removed from the page.

When I load content into a tab I attach a lot of events to elements using jQuery.

What happens when I remove these elements from the page? Does jQuery need to know?

Also, does it matter if I attach an event multiple times? For example, in my tab load I might attach an event using a class selector like $('.submitButton').click(...). But I might already have other tabs open, which have already had the submitButton event attached. In this case, I'll be re-attaching the same event. Is there any problem with this?


回答1:


If you use jQuery methods .remove() or .empty(), they will clean up all events (and other data) that were assigned with jQuery.

  • http://api.jquery.com/remove/
  • http://api.jquery.com/empty/

From the docs for remove():

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

and for empty():

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

If you used native API methods of removing, all that data will hang around. So better to use jQuery methods.




回答2:


If you remove an element with .remove() all bound events and jQuery data associated with the element is removed.

Other than .detach(), which will remove the element from the DOM, but keeps all associated data and events in memory (which is useful if you want to re-insert that element at a later time)



来源:https://stackoverflow.com/questions/3186246/do-i-need-to-detach-events-in-jquery-when-i-remove-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!