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

时间:2021-10-24 11:43:58

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...

谢谢你看…

3 个解决方案

#1


42  

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/

#2


3  

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

这在firefox上不起作用,在IE和chrome上,上面的工作都很好。

we can try on 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

但这里有两个对话框,一个是上面的消息,另一个是看起来很脏的通用消息

#3


1  

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

您应该查看onbeforeunload的MDN doc上的示例,这里有一个您正在寻找的兼容函数。

#1


42  

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/

#2


3  

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

这在firefox上不起作用,在IE和chrome上,上面的工作都很好。

we can try on 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

但这里有两个对话框,一个是上面的消息,另一个是看起来很脏的通用消息

#3


1  

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

您应该查看onbeforeunload的MDN doc上的示例,这里有一个您正在寻找的兼容函数。