当我删除元素时,是否需要在jQuery中分离事件 [英] Do I need to detach events in jQuery when I remove elements

查看:84
本文介绍了当我删除元素时,是否需要在jQuery中分离事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用动态标签的UI,因此内容可以加载到标签页中,然后标签可以关闭,内容从页面中删除。

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.

我将内容加载到选项卡中,我使用jQuery附加了大量事件。

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

当我从页面中删除这些元素时会发生什么? jQuery需要知道吗?

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

此外,如果我多次附加事件,是否重要?例如,在我的标签加载中,我可以使用类选择器附加一个事件,如 $('。submitButton')。点击(...)。但是我可能已经打开了其他选项卡,其中已经附加了submitButton事件。在这种情况下,我将重新附加相同的事件。是否有任何问题?

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?

推荐答案

如果您使用jQuery方法 .remove() .empty(),他们将清理所有分配给jQuery的事件(和其他数据)。

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/

从remove()的文档:


除了元素本身,与元素关联的所有绑定事件和jQuery数据都将被删除。

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

和空():


为了避免内存泄漏,jQuery删除其他结构例如删除元素本身之前的子元素的数据和事件处理程序。

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

如果您使用n有意义的API方法删除,所有数据将挂起。所以更好地使用jQuery方法。

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

这篇关于当我删除元素时,是否需要在jQuery中分离事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆