gpt4 book ai didi

JavaScript - 如何检查事件是否已添加

转载 作者:行者123 更新时间:2023-12-03 03:14:10 27 4
gpt4 key购买 nike

我想为 beforeunload 添加一个监听器。这是我的伪代码:

if(window.hasEventListener('beforeunload') === false) {
window.addEventListener('beforeunload', function() { ... }, false);
}

但是hasEventListener显然不存在。我怎样才能实现这个目标?谢谢。

最佳答案

事实上,不需要检查监听器是否已添加到目标:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the removeEventListener method.

来源:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#Multiple_identical_event_listeners

关于JavaScript - 如何检查事件是否已添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11430672/

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