问题描述
我遇到了jQuery(1.6.x)的奇怪问题。我在我的页面上有这个简单的调用:
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 ?'; };
但它不起作用,因为我发现,jQuery会覆盖窗口的内容.onbeforeunload。在JS控制台中,我可以看到window.onbeforeunload包含一段jQuery代码:
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;
};
有没有办法可以找到jQuery覆盖我的onbeforeunload函数的原因和位置?当我尝试使用jQuery加载和我的onbeforeunload函数运行空的jsfiddle时,它按预期工作。
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. Thanks in advance.
编辑:
以防万一,有人建议使用:
Just in case, somebody suggests using:
$(window).bind('beforeunload', function() { return 'Are you sure';} );
我已经尝试了它,它的行为与使用纯javascript的行为相同。
I've already tried it and it behaves the same way as using pure javascript.
推荐答案
好的,我终于找到了一个解决方案,这可能不是最干净的解决方案 - 因为我不知道确切的原因问题 - 但它的确有效。我已将我的beforeunload函数放入jQuery的加载函数中,因此它在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.
$(window).load(function () {
$(window).bind('beforeunload', function() { return 'Are you sure ?';} );
});
这篇关于为什么jQuery有时会覆盖window.onbeforeunload?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!