【问题标题】:Stop click event from firing停止点击事件触发
【发布时间】:2021-04-29 05:40:18
【问题描述】:

我有 2 个单独的事件监听器,第一个是点击事件,第二个是窗口 beforeunload 监听器: 这是点击事件监听器:

document.body.addEventListener('click',function(event){  
if (event.defaultPrevented) return;
console.log('click EL');
})

这是 beforeunload 监听器:

window.addEventListener("beforeunload", function (e) {
    e.preventDefault();
    console.log('beforeunload EL');
})

如果触发了 beforeunload,我可以停止触发 click 事件吗?我试过用event.preventDefault(); 做,但还是不行。

【问题讨论】:

  • 试试 e.stopPropagation();
  • @Frenchy 没用。

标签: javascript jquery dom-events addeventlistener


【解决方案1】:

试试这个,这是有效的代码:

var beforeunload = function (e) {
    e.preventDefault();
    console.log('beforeunload EL');
}

window.addEventListener("beforeunload", beforeunload);

document.body.addEventListener('click',function(event){
    if (event.defaultPrevented) return;
    console.log('click EL');
    window.removeEventListener("beforeunload", beforeunload);
});

如果您的点击发生了,只需删除监听器

【讨论】:

  • 它没有用,我也只是想让听众不要被解雇。
  • @AhmedMhadhbi 是的,您可以尝试一下吗,一旦您单击窗口将在卸载前删除,并且不会触发此操作。我已经对此进行了测试,发现它很酷,如果您看到任何其他场景,请告诉我
猜你喜欢
  • 2015-04-28
  • 2012-10-15
  • 2023-03-27
  • 2010-11-23
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多