【问题标题】:Can I use " window.onbeforeunload " twice in my html document?我可以在我的 html 文档中使用两次“window.onbeforeunload”吗?
【发布时间】:2012-06-15 23:20:19
【问题描述】:

我正在创建一个 HTML 布局,用户可以在其中填充数据并使用“保存”和“另存为草稿”分别以 HTML 和 JSON 格式保存该页面。我可以用吗

window.onbeforeunload

在我的template.html 文件中显示两次不同的警报消息?

警报将显示:

  • 当页面为空并且用户尝试去加载另一个页面时
  • 当用户在布局中填充数据并试图离开布局而不保存时

【问题讨论】:

  • 我不知道你说的两次使用它是什么意思:onbeforeunload 应该是一个函数,那么为什么不在函数中添加一个条件语句来确定要显示哪条消息呢?
  • 查看此答案以获取有关 javascript 事件绑定的更多一般信息以及用于执行此操作的各种方法:stackoverflow.com/questions/6902033/…

标签: javascript html onbeforeunload


【解决方案1】:

首先看this example 了解如果你使用它两次会发生什么,那么下面给出的想法

window.onbeforeunload=function()
{ 
    if(form_empty())
        return "Form is empty"; // message for empty form 
    else
        return "Form is not empty"; // message for filled up form 
}

function form_empty()
{
    // check form fields whether the form is empty or not
    // return true if form is empty
    // return false if form is not empty
}

【讨论】:

    【解决方案2】:

    就像以这种方式分配的任何其他事件处理程序一样,如果您再次设置它,它将破坏任何已经存在的处理程序。

    现在,如果您要根据页面状态添加和删除事件,那么这应该不是问题。否则,它有点复杂。但是,对于onbeforeunload,最好只有一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多