且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实施“此页面要求您确认是否要离开”

更新时间:2022-12-02 17:41:40

你基本上为 beforeunload 事件。这允许您警告您的用户他们有未保存的数据。

You basically implement a handler for beforeunload event. This allows you to warn your users that they have unsaved data.

伪代码:

  window.onbeforeunload = function warnUsers()
  {
    if (needToConfirm)
    {
      // check to see if any changes to the data entry fields have been made
      if(changesPresent)
            return message to display
      }
      else {
      // no changes - return nothing      
      }
    }
  }

这是一篇非常好的文章,深入讨论了这个问题: http://www.4guysfromrolla.com/webtech/100604-1.shtml

Here's a very good article that discusses this in depth: http://www.4guysfromrolla.com/webtech/100604-1.shtml

注意:还有 onunload 事件但在页面之后触发卸载,因此采取任何可靠行动为时已晚。您永远不应该在 onunload 中放置任何关键代码,因为永远不会保证执行。

Note: There is onunload event also but that fires after the page has unloaded, hence is too late to take any reliable action. You should never put any critical code in onunload as that is never guranteed to execute.