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

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

问题描述

我有一个系统,我想在用户确定他们想要在设置脏标志后离开页面时与用户核对。

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



在Chrome和FireFox中,虽然没有发生这种情况,但我可以在没有任何警告的情况下离开页面。

  if($( (body)。attr('onbeforeunload')== null){
if(window.event){
// IE和Chrome使用这个
$(body)。attr 'onbeforeunload','CatchLeavePage(event)');
}
else {
// Firefox使用这个
$(body)。attr('onbeforeunload','return false; CatchLeavePage(event)');


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

解决方案

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

  window.onbeforeunload = function(){
return你确定要离开这个页面吗? bla bla?; //你可以使这种动态的,当然...
};


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.

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.

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?

解决方案

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...
 };

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

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