beforeunload忽略条件 [英] beforeunload ignores condition

查看:117
本文介绍了beforeunload忽略条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测用户何时离开浏览器,但是我需要检查某些情况,下面的脚本跳过if(false)并始终提示请求,而不管返回true还是false.

I want to detect when user is leaving browser however I need to check on some condition, the script below skips the if(false) and always prompts for request regardless of returning true or false.

如何让它在提示之前检查条件?

How can I let it check condition before prompting?

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>

<body>

<script type="text/javascript">
    $(document).ready(function ()
    {
        $(window).bind('beforeunload', function () {
            if (false)
                return "Are you sure? Your changes will be lost!";
            else
                return false; // or true doesn't matter
        });
    });
</script>

</body>
</html>

推荐答案

我在示例中添加了一个文本框,并更改了条件,以在提示消息之前检查该值是否为1.

I've added a textbox to the example and the changed the condition to check if the value is 1 before prompting the message.

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>

<body>
<!-- added textbox for verification //-->
<input type="text" id="text1"> </input>

<script type="text/javascript">
    $(document).ready(function ()
    {
        $(window).bind('beforeunload', function () {
            //changed the if condition to check if the value of the textbox is 1 and only prompt if it is 1
            if ($('#text1').val()=="1")
                return "Are you sure? Your changes will be lost!";
        });
    });
</script>

</body>
</html>

这篇关于beforeunload忽略条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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