为什么 jQuery 有时会覆盖 window.onbeforeunload?
我在使用 jQuery (1.6.x) 时遇到了奇怪的问题。我的页面上有这个简单的调用:
window.onbeforeunload = function() { return 'Are you sure ?'; };
但它不起作用,因为据我发现,jQuery 覆盖了 window.onbeforeunload
的内容。在 JS 控制台中,我可以看到 window.onbeforeunload
包含一段 jQuery 代码:
function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined;
};
有没有办法找到 jQuery 覆盖我的 onbeforeunload
函数的原因和位置?当我尝试运行仅加载 jQuery 的空 jsfiddle 和我的 onbeforeunload 函数时,它按预期工作。
任何提示将不胜感激。
编辑:
以防万一,有人建议使用:
$(window).bind('beforeunload', function() { return 'Are you sure';} );
我已经尝试过了,它的行为与使用纯 Javascript 相同。
I am having strange problem with jQuery (1.6.x). I have this simple call on my page:
window.onbeforeunload = function() { return 'Are you sure ?'; };
But it doesn't work, because as I've found out, jQuery overwrites content of the window.onbeforeunload
. In JS console, I can see that window.onbeforeunload
contains piece of jQuery code:
function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined;
};
Is there a way I can find why and where jQuery overwrites my onbeforeunload
function? When I try to run empty jsfiddle with just jQuery loaded and with my onbeforeunload
function, it works as expected.
Any hints will be appreciated.
EDIT:
Just in case, somebody suggests using:
$(window).bind('beforeunload', function() { return 'Are you sure';} );
I've already tried it and it behaves the same way as using pure Javascript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我终于找到了一个解决方案,这可能不是最干净的解决方案 - 因为我不知道问题的确切原因 - 但它有效。我已将 beforeunload 函数放入 jQuery 的 load 函数中,以便在加载 DOM 和其他元素后执行它。
Ok, I've finally figured a solution, which is probably not the cleanest one - because I don't know the exact cause of the problem - but it works. I've put my beforeunload function into jQuery's load function so it is executed after DOM and other elements are loaded.
您可能会幸运地尝试
setTimeout(function(){ ... },0)
,我遇到了同样的问题,这是一个可行的解决方案。You might have some luck trying a
setTimeout(function(){ ... },0)
, I ran into the same problem and this worked as a viable solution.