gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:59:33 24 4
gpt4 key购买 nike

假设我有一个元素:

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

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

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

稍后,元素被删除:

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

绑定(bind)事件会发生什么?是不是也删了它徘徊吗?清理它是一个好习惯吗?

最佳答案

根据 .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 数据(这意味着您可以在分离后附加相同的元素,并且事件仍将被绑定(bind))。

关于javascript - 如果我将一个 JavaScript 事件绑定(bind)到一个元素,然后删除该元素,该事件会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34189052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com