2011-10-21 57 views
5

我有一个页面,我想确认用户是否想离开。 我必须确认,只有当特定条件得到满足,所以我写了这样的代码如何防止onbeforeunload在满足特定条件时发射?

var back=false; 
back=//check if user pressed back button 
window.onbeforeunload = function (e) { 
    alert(back); //this alerts true 
    if(back==true) 
     return false; 
     //e.preventDefault; --this does not work too 
}; 

但这不起作用。我的意思是当我点击后退按钮时,这个onbeforeunload仍然会触发,即使我返回false,我仍然会收到确认消息。什么可能是错误的? 谢谢

回答

11

如果您想向用户提供一个选项以中止卸载,则返回一个字符串。其他情况下不返回。

var back = false; 
back = true; //Somewhere, the condition is set to true 
window.onbeforeunload = function (e) { 
    if(back == true) 
     return "Are you sure to exit?"; 
} 
+1

不,你不能改变的确认消息,哈哈(开玩笑) – david

+1

@lovesh浏览器在使用标准文本中的“onbeforeunload”确认对话框的他们自己的,永远显示,而不是所有人都会显示你已经返回给用户的文本。 –

+0

@lovesh'在你的代码中返回false'**做了**。你忘记了设置'back = true'。 –

0

您还可以考虑不设置window.beforeunload事件,直到满足您的条件列表。

var confirmUserToLeave = function() { 
    if (/* conditions are met */) { 
     window.unbeforeunload = function (e) { 
      /* whatever you want to do here */ 
     }; 
    } else { 
     window.unbeforeunload = undefined; 
    } 
}; 

然后,只要在某些事件上调用该方法,可能会改变'条件得到满足'的结果。

+0

任何想法为什么在我的代码中返回false'不起作用? – lovesh

1
$(window).bind('beforeunload',function() { 
    return "'Are you sure you want to leave the page. All data will be lost!"; 
}); 

$('#a_exit').live('click',function() { 
    $(window).unbind('beforeunload'); 
}); 

试试这个。以上代码适用于大多数情况。

0

条件后端

var confirmExist = function (e) { 
    return true; 
} 
window.onbeforeunload = confirmExist; 
http get, post request 
.then(function(r)) { 
    window.onbeforeunload = null; 
} 
相关问题