window.unload() 在 jQuery 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17790256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:59:11  来源:igfitidea点击:

window.unload() won't work in jQuery

javascriptjqueryhtml

提问by Hamed Kamrava

I'm trying to alert something out after closing page.

我试图在关闭页面后提醒一些事情。

A simple window.unloadexample as below :

一个简单的window.unload例子如下:

HTML

HTML

<html>
<body>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
  <script src="test.js" type="text/javascript">
</html>

test.js

测试.js

$(window).unload( function () { 
    alert("Bye now!"); 
});

P.S :

附注:

I have tried javascript too, but doesn't alert anything out !

我也尝试过 javascript,但没有发出任何警告!

test.js

测试.js

window.onunload = function() {
    alert("Bye now!");
};

回答by RichieHindle

Most browsers prevent alertin unload. The best you can do is to use an onbeforeunloadhandler that returns a string - the browser will show that string to the user:

大多数浏览器防止alertunload。您能做的最好的事情是使用onbeforeunload返回字符串的处理程序 - 浏览器会向用户显示该字符串:

window.onbeforeunload = function() {
    return "Bye now!";
};

Demo here.

演示在这里。

回答by Tom Metcalfe

What browser are you testing this code in ?

您在什么浏览器中测试此代码?

If you check the following link from W3School, Opera and Chrome do not support it. LINK

如果您检查以下来自 W3School 的链接,Opera 和 Chrome 不支持它。关联

And a working example for onbeforeunload is to use jquery as following :

onbeforeunload 的一个工作示例是使用 jquery 如下:

    $(window).on('beforeunload', function() {
           // Do stuff
    });

(I was going to comment this last bit on the above post but I cannot yet comment :'( )

(我打算在上面的帖子上评论最后一点,但我还不能评论:'()

回答by Pieter

Use bodyor documentinstead of window.

使用bodydocument代替窗口。