javascript 如何防止 window.onbeforeunload 事件被按钮和链接事件触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17831525/
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
How to prevent window.onbeforeunload event being triggered by button and links events
提问by HBK
My form contains multiple buttons and hyperlinks and i want to show alert on back button of browser. I have used below code which works fine on Chrome and Safari but not working in IE and Firefox:
我的表单包含多个按钮和超链接,我想在浏览器的后退按钮上显示警报。我使用了以下代码,它在 Chrome 和 Safari 上运行良好,但在 IE 和 Firefox 中不起作用:
window.onload = function() {
var btnClicks = document.getElementsByClassName('noPopup');
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = setGlobal;
}
for (var i = 0; i < btnClicks.length; i++) {
btnClicks[i].onclick = setGlobal;
}
function setGlobal() {
window.btn_clicked = true;
window.linkClicked = true;
}
window.onbeforeunload = function() {
if (!window.btn_clicked || !window.linkClicked) {
return 'Would you like to save first.';
}
};
};
回答by Dziad Borowy
in IE - if you don't want the onbeforeunload
to trigger - all you need to do is to set this event to null
, like this:
在 IE 中 - 如果您不想onbeforeunload
触发 - 您需要做的就是将此事件设置为null
,如下所示:
window.onbeforeunload = null;
so what you would have to do is - add a click event listener to all your buttons and links (which redirect user to a different URI) and inside that listener - set the onbeforeunload
event listener to null
once they are clicked (before proceeding with the normal link/button action. Otherwise - set it to function (like you have in your code).
所以你需要做的是 - 添加一个点击事件监听器到你所有的按钮和链接(将用户重定向到不同的 URI)并在该监听器内部 - 将onbeforeunload
事件监听器设置为null
一旦被点击(在继续正常链接之前) /button 动作。否则 - 将其设置为功能(就像您在代码中所做的那样)。
e.g.:
例如:
document.getElementById('myLink').onclick = function () {
window.onbeforeunload = null;
};
回答by Umair Aziz
Using this beforeunload will occur only on browser close neither occur on refresh of any click of anchor and also it will act as unload event by excluding return for hiding built-in popup message on before unload event
使用此 beforeunload 只会在浏览器关闭时发生,不会在任何锚点点击刷新时发生,并且它会作为卸载事件通过排除隐藏内置弹出消息的 return 事件在卸载事件之前
function confirmExit() { $.ajax({ type: "POST", url: site_url + 'welcome_login/logout', success: function (data) { } }); } $(window).on('mouseover', (function () { window.onbeforeunload = null; })); $(window).on('mouseout', (function () { window.onbeforeunload = confirmExit; }));
Mouse Out Occurs on Closing Browser window
关闭浏览器窗口时出现鼠标移出