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

11 javascript jquery

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

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

弹出窗口很好但是当我点击"否"时,它仍然会导航......

谢谢你的期待......

Ali*_*guy 43

不需要JQuery:

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

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

  • @JesseHallett:Firefox不显示该字符串. (2认同)