jquery - 为什么 jQuery 有时会覆盖 window.onbeforeunload?

标签 jquery jquery-events 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 并使用 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 ?';} );
});

关于jquery - 为什么 jQuery 有时会覆盖 window.onbeforeunload?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7481048/

相关文章:

jquery - Gmaps4rails : map not showing when loaded dynamically

javascript - 如何从 iframe 内部捕获 iframe resize 事件(iframe 和页面 - 同一域)

javascript - 通过浏览器后退按钮访问时重新加载网站

javascript - 添加第二个 'action' 以针对不同的 div 运行

JavaScript foreach 键值数组

javascript - 如何跨浏览器检测在线/离线事件?

javascript - 将事件处理程序附加到多个文本框(具有相似的模式 ID)?

javascript - 在 beforeUnload 上发送 ajax 调用被浏览器取消

javascript - 模拟 onbeforeunload 和 onunload

jquery - 使用 jQuery 检测页面加载时鼠标悬停