Cai*_*ins 5 javascript alert onunload window.onunload
<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>
Run Code Online (Sandbox Code Playgroud)
我正在使用这个简单的代码来测试onunload和onbeforeunload的一些东西.出于某种原因,每当我刷新/离开页面并导致onunload事件时,我都不会在Firebug控制台中收到警报和错误.如果我使用onbeforeunload这工作,我没有错误,但我听说onbeforeunload不是很好的跨浏览器.
NS_ERROR_NOT_AVAILABLE: Component returned failure code: 0x80040111
(NS_ERROR_NOT_AVAILABLE) [nsIDOMWindow.alert]
alert("test");
Run Code Online (Sandbox Code Playgroud)
我没有试图提醒测试变量,只是文本"测试"之前任何人都试图指出这一点.
Bri*_*ian 13
如果你想要它可以工作,它必须在onbeforeunload事件中,但是onbeforeunload事件没有创建警报/确认弹出窗口,而是有一个内置的弹出窗口.您所要做的就是返回一个字符串,当用户尝试离开页面时,会出现弹出窗口.如果没有返回变量,则不会弹出.
一个例子如下:
<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>
Run Code Online (Sandbox Code Playgroud)
看起来你正试图在onunload事件中做一个警报.这里的问题是,为时已晚.页面已经卸载,没有停止.您可能会收到要显示的警报消息,但用户单击的内容无关紧要,因为该页面已在卸载.
你最好的选择是参加onbeforeunload活动.