beforeunload忽略条件

时间:2015-02-09 17:00:09

标签: jquery onbeforeunload

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

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

<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 个答案:

答案 0 :(得分:1)

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

<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>