Javascript 导航离开页面时如何使用 JS/jquery 进行确认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7296677/
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-24 01:40:51  来源:igfitidea点击:

How to use JS/jquery to confirm when navigating away from page

javascriptjquery

提问by AlienWebguy

I am trying to give an alert confirm dialog box when users try to navigate away...I have the following code but it doesn't quite work...

当用户尝试离开时,我试图给出一个警报确认对话框......我有以下代码但它不太工作......

    jQuery(window).unload(function() {
        var yes = confirm("You're about to end your session, are you sure?");
        if (yes) {
            return true;
        } else {
            return false;   
        }
    });

The popup comes up fine but when I click "NO", it still navigates away...

弹出窗口很好,但是当我点击“否”时,它仍然导航离开......

Thanks for looking...

谢谢你看...

回答by AlienWebguy

No need for JQuery:

不需要 JQuery:

window.onbeforeunload = function() {
    return "You're about to end your session, are you sure?";
}

Demo: http://jsfiddle.net/AlienWebguy/4fNCh/

演示:http: //jsfiddle.net/AlienWebguy/4fNCh/

回答by Mohammed Rafeeq

this does not work on firefox , on IE and chrome the above works fine.

这在 firefox 上不起作用,在 IE 和 chrome 上上述工作正常。

we can try on firefox

我们可以试试firefox

window.onbeforeunload = function() {
    return confirm("You're about to end your session, are you sure?");
}

But this presents 2 dialogue boxes one with above message and one with generic message which looks dirty

但这会显示 2 个对话框,一个是上面的消息,另一个是看起来很脏的通用消息

回答by darkodam

You should look at the example on the MDN doc for onbeforeunload, there's a compatible function for what you're looking for.

您应该查看MDN 文档上的 onbeforeunload示例,有一个兼容的功能可以满足您的需求。