Javascript Onclick事件只能运行一次

时间:2014-11-28 16:16:54

标签: javascript jquery button global-variables

这个javascript会调用一个计时器,如果满足某些变量,它会倒计时。当倒计时发生时,它会隐藏原始按钮并将其替换为另一个按钮,以便在倒计时期间不能再次调用该事件。但是,在倒计时结束后,再次单击该按钮时没有任何反应。

<div id="set_upgrade">
    <input id="upgrade" type="button" value="Upgrade" />
</div>
<div id="set_upgrading" style="display:none">
    <input id="upgrading" type="button" value="Upgrade" />
</div>
<br><br><br><br>
<p id="countdown_timer"></p>
    <script>
        document.getElementById("countdown_timer").innerHTML = ("<span id='countdown' class='timer' style='display:block'></span>");
        document.getElementById('upgrade').onclick=timer;
        document.getElementById('upgrading').onclick=alert_box;

        function display_timer(){
        };

        function alert_box(){
            alert("You are currently upgrading this module.");
        };

        var currently_upgrading = 0;
        var current_ore         = 398;
        var current_crystal     = 398;
        var upgradeTime         = 3;
        var seconds             = upgradeTime;

        var su                  = document.getElementById('set_upgrade');
        var su2                 = document.getElementById('set_upgrading');
        var su3                 = document.getElementById('countdown');

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

            su.style.display = "none";
            su2.style.display = "block";
            su3.style.display = "block";
            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) {
                su.style.display = "block";
                su2.style.display = "none";
                su3.style.display = "none";
            } else {
                seconds--;
                setTimeout(timer, 1000);
            }
        }
    </script>

1 个答案:

答案 0 :(得分:0)

首先,您不需要在每次需要执行某些操作时打开和关闭<script>标记,而不是执行onclick="alert_box();",请尝试这种方式。

function alert_box(){
    alert("You are currently upgrading this module.");
};
document.getElementById('upgrading').onclick=alert_box;