JS倒计时,不会重复执行

直接上代码,亲自测试了的,没问题咯

第一种是按钮上直接显示倒计时,

<html> 
<head> 
<title>点击获取验证码按钮后按钮变灰,倒计时一段时间后又可重复点击</title> 
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.js"></script>
</head> 
<body> 
<input type="button" id="btn" value="免费获取验证码" onclick="timer(10)" /> 
<script type="text/javascript"> 
function timer(time) {
    var btn = $("#btn");
    btn.attr("disabled", true);  //按钮禁止点击
    btn.val(time <= 0 ? "免费获取验证码" : ("" + (time) + "秒后可发送"));
    var hander = setInterval(function() {
        if (time <= 0) {
            clearInterval(hander); //清除倒计时
            btn.val("免费获取验证码");
            btn.attr("disabled", false);
            return false;
        }else {
            btn.val("" + (time--) + "秒后可发送");
        }
    }, 1000);
}
</script> 
</body> 
</html>

 第二种效果是点击按钮后,按钮被禁用,在另一处显示倒计时

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js">
    </script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #ant {
            width: 150px;
            height: 50px;
            color: red;
            text-align: center;
            line-height: 50px;
            margin: 0px auto;
        }
    </style>
    <script>
        function test() {
           
            var count = 10;
            var timer = null;
            timer = setInterval(function () {
                if (count > 0) {
                    count = count - 1;
                    $("#ant").html(count + "秒后再试");
                    $("#sendCode").attr("disabled", "disabled");
                }

                else {
                    $("#sendCode").removeAttr("disabled", "disabled");
                    $("#sendCode").html("发送验证码");
                    clearInterval(timer);
                }
            }, 1000);
        }
    </script>
</head>
<body>
    <input type="button" value="发送验证码" onclick="test()" id="sendCode" />
    <div id="ant">0</div>
</body>
</html>

有的朋友说第一种有问题,当使用来发送短信的时候,会发送两条短信,毛病还没找到,有解决了的大神麻烦指点下,谢谢了

posted @ 2016-04-11 23:21  风琴~云淡  阅读(789)  评论(0编辑  收藏  举报