Fro*_*dik 7 jquery onbeforeunload javascript-events
我有jQuery(1.6.x)的奇怪问题.我在我的页面上有这个简单的调用:
window.onbeforeunload = function() { return 'Are you sure ?'; };
Run Code Online (Sandbox Code Playgroud)
但它不起作用,因为正如我发现的那样,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;
};
Run Code Online (Sandbox Code Playgroud)
有没有办法可以找到jQuery覆盖我的onbeforeunload函数的原因和位置?当我尝试使用jQuery加载和我的onbeforeunload函数运行空的jsfiddle时,它按预期工作.
任何提示将不胜感激.提前致谢.
编辑:
为了以防万一,有人建议使用:
$(window).bind('beforeunload', function() { return 'Are you sure';} );
Run Code Online (Sandbox Code Playgroud)
我已经尝试了它,它的行为与使用纯javascript相同.
好吧,我终于找到了一个解决方案,这可能不是最干净的解决方案 - 因为我不知道问题的确切原因 - 但它有效。我已将 beforeunload 函数放入 jQuery 的 load 函数中,以便在加载 DOM 和其他元素后执行它。
$(window).load(function () {
$(window).bind('beforeunload', function() { return 'Are you sure ?';} );
});
Run Code Online (Sandbox Code Playgroud)