javascript - 使用 jQuery 在 Chrome 和 IE 中的 body 元素上设置 onbeforeunload

标签 javascript jquery google-chrome onbeforeunload

我有一个系统,我想在其中检查用户是否确定他们想要在设置脏标志后离开页面。

我正在使用以下代码 - 在 FireFox 中,我可以通过 FireBug 查看页面源代码,并且标签中正确插入了 onbeforeunload 属性。

在 Chrome 和 FireFox 中,这不会发生,我可以在没有任何警告的情况下离开页面。更新 body 标记的 jQuery 行肯定正在执行,它只是没有执行它。

if ($("body").attr('onbeforeunload') == null) {
    if (window.event) {
        // IE and Chrome use this
        $("body").attr('onbeforeunload', 'CatchLeavePage(event)');
    }
    else {
        // Firefox uses this
        $("body").attr('onbeforeunload', 'return false;CatchLeavePage(event)');
    }
}

有什么想法可以从这里开始吗?

最佳答案

您不能通过返回 false 来中止页面卸载。您必须返回将在消息框中显示给用户的字符串,并且他决定是要离开还是留在页面上(通过选择“确定”或“取消”按钮),因此您需要编写代码这个:

 window.onbeforeunload = function() {
    return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
 };

关于javascript - 使用 jQuery 在 Chrome 和 IE 中的 body 元素上设置 onbeforeunload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1802930/

相关文章:

javascript - 使用 jQuery 陷入延迟状态

javascript - 通过单击关闭模式弹出窗口

javascript - 获得同类的最后一个 child

jquery - 如何在 Td 中将启用更改为禁用?

javascript - 有人能告诉我这段代码是如何工作的吗?

html - 使用 chrome 滚动时背景无法正确加载

google-chrome - Chrome推送通知: This site has been updated in the background

javascript - 使用Browserify导入平滑滚动

javascript - 商店更新时组件不会重新呈现 - Mobx

javascript - 弹出窗口应该粘在主窗口上