因此,我知道当我对 DOM 中的元素执行 .remove() 时,它及其所有子元素都将被删除并标记为删除/垃圾收集。同样,所有元素的 jQuery UI 小部件都将触发它们的“销毁”方法,并且每个元素的 .data() 空间中的所有条目都将被删除。在决定清除我的 DOM 树的一部分时,我需要知道的是,remove 是否实际上也会显式地为每个元素触发 .off(),还是我需要自己来做?
例如,假设我有这样一系列的 div:
<div id="A-1">
<div class="HasEventListener DelegatedEventBindPoint id="B-1">
<button class="CreatesDelegatedEvent" id="C-1" />
</div>
<button class="HasEventListener NonDelegatedEvent" id="B-2" />
</div>
因此,如果我执行 $("#A-1").remove(),这是否有效地调用类似于 $(".HasEventListener").off() 的命令?
最佳答案
是的,它取消绑定(bind)所有事件处理程序。
In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
Source .
您可以使用 detach()
如果您想保留事件处理程序。
还有,你提到...
So, I know that when I execute
.remove()
on an element in the DOM, it and all its children are removed and flagged for deletion/garbage collection.
这不一定是真的。您可能仍然有对这些元素的引用。相反,引用计数将递减,如果它达到 0,则它可能被标记为 GC。
jsFiddle .
关于javascript - jquery .remove() 是否在后代 DOM 元素上触发 .off(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148943/