Are event listeners in jQuery removed automatically when you remove the element using .html()?

╄→гoц情女王★ 提交于 2019-12-04 16:19:51

问题


In jQuery if we use .remove() for removing some element, then all bound events and jQuery data associated with the elements are removed.

But what happens if we "remove" the elements with .html()?

Do we need to unbind all the elements prior to change any html for avoiding memory leaks?


回答1:


Yes, they will be removed. jQuery will clean up events etc related to the removed elements. It will NOT copy events if you do something like $(elm1).html($elm2.html())




回答2:


Yeah, they will be removed even when you use html(). The jQuery source code confirms it.




回答3:


Just to expand a bit:

  • .remove(), .html(), .empty(), etc - all remove listeners
  • .detach() does not remove listeners
  • .clone() has parameters letting you decide if data/listeners are copied

So if you want to retain listeners, use .detach().



来源:https://stackoverflow.com/questions/7549188/are-event-listeners-in-jquery-removed-automatically-when-you-remove-the-element

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