【问题标题】:Beforeunload event not working as I think it shouldBeforeunload 事件没有像我认为的那样工作
【发布时间】:2013-12-13 12:55:07
【问题描述】:

我希望用户在尝试离开我的页面时收到一条消息。我的页面由一个表格和一些链接(菜单等)组成。我的 jQuery 代码如下

$(document).ready(function(){
    $(window).bind('beforeunload', function(e){
        answer=confirm('Do you want to go?');
        if (answer===false){
            e.preventDefault();
        }
    });
});

但是,当我单击其中一个链接时,用户在页面外导航,并且没有出现任何确认对话框。我误解了beforeunload 事件吗?

【问题讨论】:

标签: jquery onbeforeunload


【解决方案1】:

不幸的是,没有办法覆盖默认行为。大多数浏览器只会显示事件的返回值,并伴有“确定”/“离开页面”和“取消”按钮。您可以设置该消息:

window.onbeforeunload = function (e) {
        var e = e || window.event;
        // For IE and Firefox prior to version 4
        if (e) {
            e.returnValue = 'Hey, you are leaving. Do you want to continue?';
        }
        //you can do some last minute scripting here
        // For Safari
        return 'Hey, you are leaving. Do you want to continue?';
};

根据 Jason P 的建议,read more on it here

【讨论】:

    猜你喜欢
    • 2019-01-19
    • 1970-01-01
    • 2011-09-29
    • 2016-06-19
    • 2013-04-11
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多