2

此代码将导致 Internet Explorer 显示“您确定要离开吗?” 每次都发送消息,即使dirtyMessage 为空。我究竟做错了什么?

$(window).bind('beforeunload', function() {
  var dirty = didUserUpdateSomething();  

  if (dirty) {
    return "You will lose your changes.";
  }
  return null;
});
4

2 回答 2

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'.
});
于 2013-05-13T18:07:42.300 回答
0

The beforeunload in IE is a bit quirky; Returning ANYTHING in your event handler (even null) will cause it to pop up a box asking the user if the user is quite sure they want to leave the page.

You can try this as a possible workaround:

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;
}

Couple of references: https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/beforeunload?redirectlocale=en-US&redirectslug=Mozilla_event_reference%2Fbeforeunload

and

http://msdn.microsoft.com/en-us/library/ie/ms536907(v=vs.85).aspx

NOTE: see the "Remarks" for pertinent information within that second reference.

于 2013-05-13T18:20:48.953 回答