【问题标题】:Enable button when counter reaches zero计数器归零时启用按钮
【发布时间】:2017-05-28 18:53:51
【问题描述】:

我有一个禁用的按钮,我想在里面放一个计数器,我想做的是当计数器达到零时它被启用,我该怎么做?在下面的代码中,计数器没有出现在按钮内,我不希望重置按钮,我只希望按钮在达到零时启用,这是我迄今为止尝试过的:

function Countdown()
{
    this.start_time = "00:30";
    this.target_id = "#timer";
    this.name = "timer";
    this.reset_btn = "#reset";
}

Countdown.prototype.init = function()
{
this.reset();
setInterval(this.name + '.tick()',1000)
}

Countdown.prototype.reset = function()
{
    $(this.reset_btn).hide();
    time = this.start_time.split(":");
    //this.minutes = parseInt(time[0]);
    this.seconds = parseInt(time[1]);
    this.update_target();
}

Countdown.prototype.tick = function()
{
    if(this.seconds > 0) //|| this.minutes > 0)
    {
        if(this.seconds == 0)
        {
           // this.minutes = this.minutes - 1;
            this.seconds = 59
        } else {
        this.seconds = this.seconds - 1;
        }
    }
    this.update_target()
}

Countdown.prototype.update_target = function()
{
    seconds = this.seconds;
    if (seconds == 0) $(this.reset_btn).show();
    else if(seconds < 10) seconds = "0" + seconds;
    $(this.target_id).val(this.seconds)
}

timer = new Countdown();
timer.init();

$(document).ready(function(){
    $("#reset").click(function(){
        //timer = new Countdown();  
        timer.reset();
    });
});
.hidden {
    display: none;
}
<button type="text" id="timer" disabled>Counter should be inside me, and enable me when it reaches 0</button>
         <button id="reset">Reset</button>

【问题讨论】:

  • 如果你不使用 jQuery 并且没有用它标记你的问题,为什么还要包含它?

标签: javascript button counter


【解决方案1】:

这比你得到的要简单得多。只需使用 window.setTimeout()

请记住,在浏览器中以高精度跟踪时间并不是非常可靠的。您可能想查看 moment.js 或使用 performance.now() 以获得更简单的 API 来处理它。

// Get refreence to span and button
var spn = document.getElementById("count");
var btn = document.getElementById("btnCounter");

var count = 5;     // Set count
var timer = null;  // For referencing the timer

(function countDown(){
  // Display counter and start counting down
  spn.textContent = count;
  
  // Run the function again every second if the count is not zero
  if(count !== 0){
    timer = setTimeout(countDown, 1000);
    count--; // decrease the timer
  } else {
    // Enable the button
    btn.removeAttribute("disabled");
  }
}());
&lt;button id="btnCounter" disabled&gt;Time left: &lt;span id="count"&gt;&lt;/span&gt;&lt;/button&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    相关资源
    最近更新 更多