5
<html>
<body>

<button type="button" onclick="clickme()">Click Me</button>

<script>
var test = 0;

function clickme() {
  test = 1;
  console.log(test);
}

window.onunload = function() {
  alert("test");
}
</script>

</body>
</html>

我正在使用这个简单的代码来测试一些关于 onunload 和 onbeforeunload 的东西。出于某种原因,每当我刷新/离开页面并导致 onunload 事件时,我在 Firebug 控制台中都没有收到警报和错误。如果我使用 onbeforeunload 这工作并且我没有收到错误,但我听说 onbeforeunload 不是很好的跨浏览器。

NS_ERROR_NOT_AVAILABLE: Component returned failure code: 0x80040111     
(NS_ERROR_NOT_AVAILABLE) [nsIDOMWindow.alert]

alert("test");

我不是想提醒测试变量,只是在任何人试图指出之前提醒文本“测试”。

4

1 回答 1

13

如果你想让它工作,它必须在 onbeforeunload 事件中,但不是创建警报/确认弹出窗口,onbeforeunload 事件有一个内置的弹出窗口。您所要做的就是返回一个字符串,当用户试图离开页面时,弹出窗口就会出现。如果没有返回变量,则不会弹出。

  • 这样做的好处是弹出消息有 2 个按钮:确定和取消。
  • 如果用户点击 OK,浏览器将继续导航离开该页面
  • 如果用户点击取消,浏览器将取消卸载并停留在当前页面
  • onbeforeunload 事件是唯一可以取消 onunload 事件的弹窗

下面是一个例子:

<script type="text/javascript">

window.onbeforeunload=before;
window.onunload=after;

function before(evt)
{
   return "This will appear in the dialog box along with some other default text";
   //If the return statement was not here, other code could be executed silently (with no pop-up)
}

function after(evt)
{
   //This event fires too fast for the application to execute before the browser unloads
}

</script>

您似乎正试图在 onunload 事件中发出警报。这里的问题是为时已晚。该页面已经在卸载并且没有停止它。您可能会收到一条要显示的警报消息,但用户点击什么并不重要,因为该页面已经在卸载。

最好的选择是使用 onbeforeunload 事件。

于 2013-06-04T17:37:53.550 回答