如何在遇到某个条件时阻止onbeforeunload触发? [英] how can i prevent onbeforeunload from firing when a certain condition is met?

查看:150
本文介绍了如何在遇到某个条件时阻止onbeforeunload触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,我想确认用户是否想要离开。
我只有在满足某个条件时才需要确认,所以我写了这样的代码

i have a page on which i want to confirm if the user wants to leave. i have to confirm only when a certain condition is met so i wrote code like this

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,我仍然会收到确认消息。什么可能是错的?
谢谢

but this does not work. i mean when i click on back button this onbeforeunload still fires and i still get the confirmation message even when i m returning false.Whats can be wrong? Thanks

推荐答案

如果要为用户提供中止卸载的选项,请返回一个字符串。在其他情况下不返回任何内容。

Return a string if you want to offer an option to the user to abort the unload. Return nothing in other cases.

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?";
}

这篇关于如何在遇到某个条件时阻止onbeforeunload触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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