$(窗口).unload没有触发

我想在用户使用jQuery放弃特定页面时执行一个动作方法。

该页面包含以下代码:

 $(window).unload(function () { alert("Handler for .unload() was called."); });  

当我离开页面时,我从未看到预期的警报。

实际上,如果您尝试在窗口中unload alert ,某些浏览器(例如Google Chrome)可能会阻止。 作为用户,我喜欢这个function。 每当您尝试离开页面时发出警报:

在此处输入图像描述

使用console.log或其他不太干扰用户的内容替换警报,并且可以愉快地调用事件。

您可能还想查看onbeforeunload事件。

jquery .on(’unload’,..); 对我来说不可靠。 我切换到使用beforeunload。 只是确保你没有返回任何东西,或者用户将得到“你确定要离开页面”-popup。

  

正如bhelm所说, beforeunload也适用于我。
对此事件返回false将调用浏览器默认值

你确定要离开这个页面吗?

 $(window).on('beforeunload', function () { return false; }); 
 window.onbeforeunload=navigationError; var dont_confirm_leave = 0; var leave_message = 'You sure you want to leave?'; function navigationError(e) { if(dont_confirm_leave!==1) { if(!e) e = window.event; //e.cancelBubble is supported by IE - this will kill the bubbling process. e.cancelBubble = true; e.returnValue = leave_message; //e.stopPropagation works in Firefox. if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } //return works for Chrome and Safari return leave_message; } } 

如果你想提醒用户你离开这个页面,那么这个

 /* $(window).unload(function() { //alert("you leaving this page"); console.log("you leaving this page"); }); */