如果我将一个 JavaScript 事件绑定到一个元素,然后删除该元素,该事件会发生什么?

If I bind a JavaScript event to an element, then delete the element, what happens to the event?

假设我有一个元素:

<section id="container">
    <div id="curious">hey, there</div>
</section>

然后,在 DOM 加载后,我将事件绑定到元素,如下所示:

$('#curious').click(function (){
  alert('Are you curious?');
});

稍后,元素被删除:

$('#container').html('');

绑定的事件会怎样?是不是也删了它徘徊吗?清理它是个好习惯吗?

根据 .html() method 的 jQuery 文档,删除了事件处理程序。

这样做是为了防止内存泄漏。

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

同样,使用.empty()/.remove()方法时也是如此:

all bound events and jQuery data associated with the elements are removed.

如果要保留数据和事件侦听器,请改用 .detach() method.detach() 方法本质上与 .remove() 方法相同,除了它保留与删除元素关联的所有 jQuery 数据(这意味着您可以在分离后附加相同的元素它,并且事件仍然会被绑定)。