【问题标题】:How to remove the body unload event? [duplicate]如何删除正文卸载事件? [复制]
【发布时间】:2021-08-15 02:03:37
【问题描述】:

我有以下 body 卸载事件监听器

  window.onbeforeunload = () => {
     return "Changes you made may not be saved.";
  };

当我完成了我必须做的后台处理后,如何删除那个特定的?

【问题讨论】:

  • window.onbeforeunload = null
  • 如果页面上有多个卸载前我只想取消那个怎么办?
  • 怎么会有?您只绑定一个处理程序。

标签: javascript


【解决方案1】:

要删除一个事件监听器(就像你提到的多个事件监听器的情况), 您需要将事件处理函数命名为外部函数,而不是匿名的(以便您可以引用该函数):

更新 1:- 我已在屏幕上添加了要关注的消息

   

 window.addEventListener("beforeunload", customFunction);

    function customFunction(event){
        event.preventDefault();
        return event.returnValue = "Are you sure you want to exit?";
    }
    window.removeEventListener("beforeunload",customFunction);

【讨论】:

  • 如果我想显示一个警告以防止用户关闭标签,我应该在 customFunction 正文中输入什么?
  • 我已经更新了我的答案
猜你喜欢
  • 2011-06-26
  • 2023-03-04
  • 2010-09-16
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
相关资源
最近更新 更多