在 jQuery 中,如果删除一个元素,该元素上的任何事件都会被删除吗?
例如,如果我有一个链接,其中绑定了以下事件:
$("a.d").bind("click", this, onDelete);
然后执行:
$("a.d").remove();
可以吗?或者它会导致内存泄漏,我需要先调用 unbind 吗?
感谢您的任何帮助。
For example if I have a link with the following event bound to it:
$("a.d").bind("click", this, onDelete);
And later do:
$("a.d").remove();
Is that fine? Or does it cause a memory leak and I need to call unbind 1st?
Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 jQuery 文档中的remove()
From jQuery docs for remove()
我还没有测试过它,但我相信删除元素将解除其事件处理程序的绑定。我从 jQuery API 文档(搜索删除)得出这个结论,其中指出如果您想移动从 DOM 的一个部分到另一部分的元素:
应编写以
避免丢失事件处理程序。
I haven't tested it, but I believe that removing an element will unbind its event handlers. I come to this conclusion from the jQuery API documentation (search for remove) which states that if you want to move an element from one part of the DOM to another that:
should be written as
to avoid losing the event handlers.
答案是肯定的,只要该事件是用 jQuery 附加的。如果附加诸如“onclick”之类的东西,我不相信它会。
本文讨论了其中的一些内容。它还定义了一个递归函数来删除元素及其所有子元素的所有单击事件。它将涵盖 jQuery 单击处理程序以及使用 onclick 定义的处理程序,以便您了解。
http://www. Computerhowtoguy.com/how-to-use-the-jquery-unbind-method-on-all-child-elements/
要使用前面示例中的函数,我们将调用该函数并将其传递给“容器”div作为 jQuery 对象。
The answer is yes, so long as the event was attached WITH jQuery. If attached with something like "onclick" I don't believe it will.
This article discusses some of that. It also defines a recursive function to remove all click events for an element and all of its children. It will cover jQuery click handlers as well as handlers defined with onclick so you're covered.
http://www.computerhowtoguy.com/how-to-use-the-jquery-unbind-method-on-all-child-elements/
To use the function in the previous example we would call the function passing it the “container” div as a jQuery object.
根据记录,您不必担心 javascript 中的内存泄漏。 (冷静点,不是 C++!)
浏览器的 javascript 引擎管理所有对象,并且垃圾收集它们。当我说对象时,这也意味着事件处理函数,因为函数也是 javascript 中的对象。
无关:我喜欢 javascript 中的一切都是对象:D
干杯!
杰瑞赫
For the record, you need not worry about memory leaks in javascript. (chill man, not c++!)
The browser's javascript engine manages all objects, and garbage collects them. When I say objects, that means event-handling-functions too, because functions are also objects in javascript.
Unrelated: I love how everything is an object in javascript :D
Cheers!
jrh