Javascript:删除相关 HTML 时是否应该删除事件处理程序?

标签 javascript jquery event-handling unbind

我的页面上有以下 HTML:

<div class="component">
  <a href="#" class="delete">delete</a>
</div>

我在页面加载时有以下脚本:

$(document).ready(function(){

  $('a.delete').on('click', function() {
    ....
  });

});

此页面还有其他 Javascript 代码,可操作该页面并通过以下方式删除:

$('.component').remove();

我的问题:在删除 HTML 之前是否需要删除(取消绑定(bind))事件处理程序?如果不是的话,会不会有内存泄漏或者其他影响?

感谢和问候!

最佳答案

因为您使用的是 jQuery,所以您无需担心它。

Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

http://api.jquery.com/remove/ (强调已添加)

关于Javascript:删除相关 HTML 时是否应该删除事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18601347/

相关文章:

java - 如何在单击事件时一次仅验证一个文本框

c# - 按住鼠标时多次引发事件

javascript - ReactJS - 无法读取新路由器未定义的属性 'location'

javascript - 在 HTML 页面中显示 XML 内容以创建表单元素

javascript - JEST Received 函数没有抛出,但是抛出了 HTTPError

javascript - JQuery 通过键从 json 中获取值

javascript - 如何阻止内容脚本自行启动

javascript - 如何在(AngularJS)ui-select 组件中设置搜索输入的最大长度?

Jquery Colorbox 滚动整个窗口,而不仅仅是 colorbox 内的内容

c# - 将我自己的参数发送给事件处理程序?