1

我编写了以下代码来在卸载中运行 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?";
}
4

2 回答 2

5

onunload事件是当用户离开页面或关闭浏览器时触发的绝对最后一个事件。

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?";
    }
});
于 2012-09-17T01:46:33.643 回答
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?");
于 2012-09-17T01:49:22.723 回答