javascript - 为什么即使在 Internet Explorer 中返回 null,jquery beforeunload 也会显示一条消息

标签 javascript jquery onbeforeunload

此代码将使 Internet Explorer 显示“您确定要离开吗?”每次都会收到消息,即使 dirtyMessage 为 null 时也是如此。我做错了什么?

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

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

最佳答案

显然返回 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'.
});

关于javascript - 为什么即使在 Internet Explorer 中返回 null,jquery beforeunload 也会显示一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16528365/

相关文章:

javascript - 找不到我的 JavaScript 函数

javascript - 是否可以使用 puppeteer 将屏幕截图与网页的 ui 元素进行比较并找出差异?

javascript - 创建可点击 Material 图标时出现 Linting 错误

javascript - 如何跟踪实时输入值并提交到服务器?

PHP 反序列化 jQuery FORM 帖子

javascript - 如何在jquery函数中获取console.log数据

jquery - 将同一行上的所有 DIVS 设置为相同的高度......但每行不同

safari - 当用户关闭Safari/Chrome中的窗口时,可以弹出确认对话框吗?

javascript - 当用户退出浏览器时显示自定义对话框?

javascript - 让 onBeforeUnload 与 setTimeout 一起工作