我需要在删除元素之前取消绑定jquery事件吗? [英] Do I need to unbind jquery event before remove element?

查看:64
本文介绍了我需要在删除元素之前取消绑定jquery事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用jquery-ui-dialog的页面.每次打开对话框时,页面内容都会使用ajax加载.然后,它使用jquery"on()"绑定某些事件. 对话框关闭时,它将清空其内容.

I have a page using jquery-ui-dialog. Each time the dialog opens, page contents load in using ajax. Then it binds some event using jquery "on()". When the dialog close, it will empty its content.

问题是,我是否需要取消$ .empty()之前的".ajax-content"上的事件的绑定?

The question is, do I need to unbind the events on ".ajax-content" before $.empty()?

编辑 : 关注1.是否可能降低JS性能?如果我以这种方式清空()数百个节点.

edit: concern 1. any possible degrade JS performance? if I empty() hundreds of nodes this way.

关注点2. 是否要删除元素,是否还会从内存中删除事件(或jquery的任何执行/评估链)?

concern 2. would remove element also remove events from memory(or whatever execution/evaluation chain of jquery)?

我暂时不对他们做任何事情. 如果对话框多次打开/关闭而不刷新页面,是否会引起任何问题?

I am not doing anything to them for now. If the dialog open/close for many times without page refresh, would it cause any problem?

代码如下:

<div id="jquery-dialog" class="container">
  <div class="ajax-content">
    some buttons....
  </div>
</div>

------after each ajax load------------
$(".ajax-content").on("click", ".button", function(event) {
  //handles the click
});

------on dialog close------------
$("#jquery-dialog").empty();

推荐答案

嘿,我知道这是一个老问题,但我相信公认的答案会产生误导.

Hey I know this is an old question but I believe the accepted answer is misleading.

尽管正确地说,您将需要取消绑定原始JS上的事件以避免旧浏览器(ehem IE)上的内存泄漏,但调用remove()或empty()已经为您完成了.

Although it's correct to say that you will need to unbind events on raw JS to avoid memory leaks on old browsers (ehem IE), calling remove() or empty() will already do that for you.

因此您当前对empty()的调用就足够了,不需要在其之前加上unbind()

So your current call to empty() should be enough, it doesn't need to be preceded by unbind()

从jQuery文档( http://api.jquery.com/empty/)

From jQuery docs (http://api.jquery.com/empty/)

为避免内存泄漏,jQuery在删除元素本身之前先从子元素中删除其他构造,例如数据和事件处理程序.

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

这篇关于我需要在删除元素之前取消绑定jquery事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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