Javascript函数在单击按钮之前激活

时间:2014-11-28 14:27:28

标签: javascript php jquery function

如果单击按钮时满足要求,则会显示倒计时器。问题是它甚至在你点击按钮之前显示倒数计时器。我不确定我在忽视什么。

 <input id="upgrade" type="button" value="Upgrade" onclick="timer();" />
 <br><br><br><br>
 <p id="countdown_timer"></p>

<script>
    function display_timer(){
        document.getElementById("countdown_timer").innerHTML = "<span id='countdown' class='timer'></span>";
    }
</script>

<script>
    var currently_upgrading = 0;
    var current_ore         = 398;
    var current_crystal     = 398;
    var upgradeTime  = 172801;
    var seconds      = upgradeTime;

    function timer() {
        if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
        if(current_ore <= 299){alert('You need more ore.');return;}
        if(current_crystal <= 299){alert('You need more crystal.');return;}

        display_timer();
        var days        = Math.floor(seconds/24/60/60);
        var hoursLeft   = Math.floor((seconds) - (days*86400));
        var hours       = Math.floor(hoursLeft/3600);
        var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
        var minutes     = Math.floor(minutesLeft/60);
        var remainingSeconds = seconds % 60;

        if (remainingSeconds < 10) {
            remainingSeconds = "0" + remainingSeconds; 
        }
        document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
        if (seconds == 0) {
            clearInterval(countdownTimer);
            document.getElementById('countdown').innerHTML = "Completed";
        } else {
            seconds--;
        }
    }
    var countdownTimer = setInterval('timer()', 1000);
</script>

4 个答案:

答案 0 :(得分:2)

您需要将countdownTimer变量移动到timer()函数中。

答案 1 :(得分:1)

这一行

var countdownTimer = setInterval('timer()', 1000);

将在页面加载后以及单击按钮时执行1秒钟,这将调用display_timer函数。

答案 2 :(得分:1)

你已经在setInterval函数中调用它,所以它会立即启动,因为setInterval函数在页面加载后运行而不是单击而setInterval使用你的函数

答案 3 :(得分:1)

尝试将timer()的最后一行更改为:

    if (seconds == 0) {
        document.getElementById('countdown').innerHTML = "Completed";
    } else {
        seconds--;
        setTimeout(timer, 1000);
    }

并删除setInterval行。

一般来说,setTimeoutsetInterval更受欢迎,因为它不需要托管状态(在您的示例中为countdownTimer),并且更加灵活。

另请注意,传递setTimeout('timer()', 1000)中的字符串已过时,只需传递一个函数:setTimeout(timer, ...)