【问题标题】:Checkbox when unchecked未选中时的复选框
【发布时间】:2016-06-24 00:35:33
【问题描述】:

我试图让复选框在选中时执行计时事件,并在未选中时停止。选中时它可以工作,但是当我取消选中它时,它只是再次执行该功能,变量变得更快。

Live

JS 代码

var money = 0;

function moneyMaker(){
    money++;
  document.getElementById('money').innerHTML = money;
}

function doautoMoney(){
    window.setInterval(function(){

        moneyMaker();
        document.form.automoney.click();
        //alert('Auto Saved!');
    }, 1000); 
}

【问题讨论】:

    标签: javascript checkbox


    【解决方案1】:

    使用 clearInterval() 清除未选中的间隔,而不是 onclick 在复选框的情况下使用 onchange

    var money = 0;
    
    function moneyMaker() {
      money++;
      document.getElementById('money').innerHTML = money;
    }
    var int;
    
    function doautoMoney(chk) {
      if (chk)
        // store the interval reference for clearing the interval
        int = window.setInterval(function() {
          moneyMaker();
          //document.form.automoney.click();
          //alert('Auto Saved!');
        }, 1000);
      else
        clearInterval(int)
    }
    Money: <span id="money">0</span>
    <p>
      <button onclick="moneyMaker(1)">Mine Iron!</button>
      <input type="checkbox" name="automoney" onchange="doautoMoney(this.checked);">

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-21
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 2016-12-22
      • 2014-03-21
      • 1970-01-01
      相关资源
      最近更新 更多