beforeunload ignores condition

ぐ巨炮叔叔 提交于 2019-12-11 11:34:47

问题


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>


来源:https://stackoverflow.com/questions/28415129/beforeunload-ignores-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!