使用 jQuery 在 Chrome 和 IE 中的 body 元素上设置 onbeforeunload [英] Setting onbeforeunload on body element in Chrome and IE using jQuery

查看:37
本文介绍了使用 jQuery 在 Chrome 和 IE 中的 body 元素上设置 onbeforeunload的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个系统,我想与用户确认一旦设置了脏标志,他们是否确定要离开页面.

I have a system where I want to check with the user if they're sure they want to leave the page once a dirty flag is set.

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

I'm using the following code - In FireFox, I can look at the page source through FireBug and the tag correctly has the onbeforeunload attribute inserted in it.

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

In Chrome and FireFox, this doesn't happen though and I'm able to navigate away from the page without any warning at all. The jQuery line to update the body tag is definitely being executed, it just isn't performing it.

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)');
    }
}

任何想法如何从这里开始?

Any ideas how to proceed from here?

推荐答案

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

you cannot abort page unload by returning false. you must return string that will be shown to user in a message box, and he decides if he want to leave or stay on the page (by selecting either 'OK' or 'Cancel' button), so you need to write your code like this:

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

这篇关于使用 jQuery 在 Chrome 和 IE 中的 body 元素上设置 onbeforeunload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆