$(窗口).unload没有触发

时间:2012-02-21 21:52:19

标签: jquery onbeforeunload

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

该页面包含以下代码:

    <script type="text/javascript">

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

    </script>

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

6 个答案:

答案 0 :(得分:30)

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

enter image description here

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

您可能还想查看onbeforeunload事件。

答案 1 :(得分:12)

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

<script type='text/javascript'>
    $(window).on('beforeunload', function(){
         console.log("beforeUnload event!");
     });
</script>

答案 2 :(得分:6)

巴勒姆说 beforeunload 也适合我。
在此事件上返回false将调用浏览器默认值

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


$(window).on('beforeunload', function ()
    {
        return false;
    });

答案 3 :(得分:2)

在我的许多项目中,此处提到的方法不稳定对我来说唯一有用的是将事件绑定为body元素上的原始属性

<body onunload="my_function_unload()">

jQuery方法:

$('body').attr('onunload', 'my_function_unload()');

在iframe中:

<body onunload="window.parent.my_function_unload()">

jQuery方法:

$('<iframe />').load(function(){
    $body = $(this).contents().find('body');
    $body.attr('onunload', 'window.parent.my_function_unload()');
}

此外,重要,属性中没有参数,并且该函数必须在全局窗口范围内,否则不会发生任何事情。

例如常见错误,如果您的my_function_unload()放在;( function( $ ) {...$(document).ready(function(){... AS my_function_unload()中,则必须在该私有范围之外。并且不要忘记使用jQuery而不是$前缀。

答案 4 :(得分:0)

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;
    }
  }

答案 5 :(得分:0)

如果您想提醒用户您离开此页面,那么

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

功能不起作用,然后用on(&#34; beforeunload&#34;,function)代替你的代码

&#13;
&#13;
$(window).on("beforeunload", function()
{
	alert("you leaving this page");
	console.log("you leaving this page");
});
&#13;
&#13;
&#13;

这项工作对我来说!你可以在控制台日志中看到输出 you leaving this page