Javascript 禁用链接的 onbeforeunload

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4084152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:32:02  来源:igfitidea点击:

Disable onbeforeunload for links

javascriptjquery

提问by dzm

How can I disable onbeforeunload for links?

如何禁用链接的 onbeforeunload?

var show = true;

function showWindow(){
    if(show){      
        alert('Hi');
        return "Hi Again";
    }
}


$('a').click(function(){

    show = false;

});


window.onbeforeunload = showWindow;

This is what I have, but it still shows when I click on an 'a' element

这就是我所拥有的,但是当我单击“a”元素时它仍然显示

Button code:

按钮代码:

<button type="submit" class="submitBtn"><span>Open Account</span></button>

回答by JustcallmeDrago

Instead of

代替

show = false;

try

尝试

window.onbeforeunload = null;

This will simply unbind the function from the event.

这将简单地解除函数与事件的绑定。

回答by Ginchen

I just ran into the same problem and found a very easy solution:

我刚刚遇到了同样的问题,并找到了一个非常简单的解决方案:

$("a").mousedown(function() {
    $(window).unbind();
});

This will remove the onbeforeunload event just before the click event is triggered.

这将在触发 click 事件之前移除 onbeforeunload 事件。

回答by qasimzee

Use following code to unbind the event:

使用以下代码解除事件绑定:

javascript:window.onbeforeunload=function(){null}