我编写了以下代码来在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?";
}
答案 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?");