简体   繁体   English

停止点击事件触发

[英]Stop click event from firing

I have 2 seperate event listeners, the first one is a click event, second one is a window beforeunload listener: This is the click event listener:我有 2 个单独的事件监听器,第一个是点击事件,第二个是 window beforeunload 监听器:这是点击事件监听器:

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

and this is the beforeunload listener:这是 beforeunload 监听器:

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

Can I stop the click event from firing if the beforeunload is fired?如果触发了 beforeunload,我可以停止触发 click 事件吗? I've tried doing it with event.preventDefault();我试过用event.preventDefault(); still it didn't work.仍然没有用。

Try this, This is working code:试试这个,这是工作代码:

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);
});

Just remove the listener if your click happened如果您的点击发生,只需删除侦听器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM