onbeforeunload在卸载时无法正常工作

时间:2012-09-17 01:42:52

标签: javascript jquery

我编写了以下代码来在unload中运行onbeforeunload。但是,这似乎不起作用。有没有人知道我的代码有什么问题,无论如何要让它运作起来?

$(window).unload(function () {
    if ($('.submitAction').val() == "" && isChange) {
        window.onbeforeunload = confirmExit;
    }
});

function confirmExit() {
    return "If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}

2 个答案:

答案 0 :(得分:5)

onunload事件是当用户离开页面或关闭浏览器时触发的absolute last event

绑定到 onbeforeunload事件中的onunload事件将毫无意义,因为此事件已经发生(因此名称​​ onbeforeunload ) 。解决方案是在事件实际发生之前绑定到onbeforeunload事件,例如页面加载时。

像这样(未经测试):

$(window).bind('beforeunload', function () {
    if ($('.submitAction').val() == "" && isChange) {
       return "If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
    }
});

答案 1 :(得分:0)

此行返回一个字符串:

return "If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";

我认为你的意思是:

return window.confirm("If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?");