此代码将导致Internet Explorer显示“您确定要离开吗?”每次都有消息,即使dirtyMessage为null。我做错了什么?
$(window).bind('beforeunload', function() {
var dirty = didUserUpdateSomething();
if (dirty) {
return "You will lose your changes.";
}
return null;
});
答案 0 :(得分:4)
显然返回null是问题所在。适用于除旧IE之外的所有其他浏览器。解决方案不是返回任何内容(未定义):
$(window).bind('beforeunload', function() {
var dirty = didUserUpdateSomething();
if (dirty) {
return "You will lose your changes.";
}
// notice that in case of no dirty message we do not return anything.
// having 'return null;' will make IE show a popup with 'null'.
});
答案 1 :(得分:0)
IE中的beforeunload
有点古怪;在事件处理程序中返回任何内容(甚至为null)将导致它弹出一个框,询问用户用户是否确定要离开页面。
您可以尝试将其作为可能的解决方法:
var beforeUnloadFired = false;
$(window).bind('beforeunload', function (event) {
if (!beforeUnloadFired) {
beforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. Are you sure you want to navigate away from this page?";
}
window.setTimeout(function () {
ResetUnloadFired();
}, 10);
});
function ResetUnloadFired() {
beforeUnloadFired = false;
}
和
http://msdn.microsoft.com/en-us/library/ie/ms536907(v=vs.85).aspx
注意:请参阅“备注”以了解该第二次参考中的相关信息。