删除 ID 为 #foo
的 DOM 元素是否会分离所有引用该 ID 的 jQuery 监听器?例如,如果我在 $('#foo #bar')
上有一个监听器,它是否也会自动删除? (我正在使用 elem.parentNode.removeChild(elem)
方法删除元素。)
如果我必须手动清理,是否使用 jQuery .off()
方法,如 $('#foo').off()
也会分离所有监听器我使用 $('#foo #bar').on('click', myFunction)
附加了它,还是只是分离?
最佳答案
Does deleting a DOM element with the id #foo detach all jquery listeners that reference that id?
如果您使用 jQuery 来执行它,它会执行此操作,例如:
$("#foo").remove();
jQuery 会为您处理清理工作。来自 the documentation :
In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
(我的重点)
稍后,在示例删除 <div class="hello">
之后:
If we had any number of nested elements inside
<div class="hello">
, they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.
(我的重点)
关于javascript - 从已删除的 DOM 元素中分离 jQuery 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50913782/