1. 程式人生 > >js實現傳送簡訊驗證碼後60秒倒計時

js實現傳送簡訊驗證碼後60秒倒計時

1、input[type=‘button’]按鈕 js方法實現
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var countdown=60;
function settime(obj) {
    if (countdown == 0) {
        obj.removeAttribute("disabled");    
        obj.value="免費獲取驗證碼";
        countdown = 60;
        return;
    } else {
        obj.setAttribute("disabled", true);
        obj.value="重新發送(" + countdown + ")";
        countdown--;
    }
setTimeout(function() {
    settime(obj) }
    ,1000)
}
 
</script>
<body>
<input type="button" id="btn" value="免費獲取驗證碼" onclick="settime(this)" />
</body>
</html>


2、jquery方法實現

button按鈕 需要時呼叫即可 傳遞id或class等。

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
function invokeSettime(obj){
    var countdown=60;
    settime(obj);
    function settime(obj) {
        if (countdown == 0) {
            $(obj).attr("disabled",false);
            $(obj).text("獲取驗證碼");
            countdown = 60;
            return;
        } else {
            $(obj).attr("disabled",true);
            $(obj).text("(" + countdown + ") s 重新發送");
            countdown--;
        }
        setTimeout(function() {
                    settime(obj) }
                ,1000)
    }
}

  new invokeSettime("#btn");

</script>
<body>
    <button id="btn" type="button">獲取驗證碼</button>
</body>
</html>