我在使用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并使用onbeforeunload
函数运行空的jsfiddle时,它会按预期运行。
任何提示将不胜感激。
编辑:
以防万一,有人建议使用:
$(window).bind('beforeunload', function() { return 'Are you sure';} );
我已经尝试过了,它的行为与使用纯Javascript相同。
好吧,我终于找到了一种解决方案,它可能不是最干净的解决方案-因为我不知道问题的确切原因-但它可行。我将我的beforeunload函数放入jQuery的load函数中,以便在DOM和其他元素加载后执行。
$(window).load(function () {
$(window).bind('beforeunload', function() { return 'Are you sure ?';} );
});
您可能在尝试setTimeout(function(){ ... },0)
时有些运气,我遇到了同样的问题,这是可行的解决方案。