【问题标题】:How to use an interval and a function to change the innerHTML of a div?如何使用间隔和函数来更改 div 的 innerHTML?
【发布时间】:2019-03-27 14:53:07
【问题描述】:

所以我希望innerHTML 到 div("gamediv") 在计时器达到 0 时更改。在 div("gamediv") 中,还有另一个应该触发该功能的 div。但现在的情况是,计时器在加载时启动,g1change() 永远不会发生。

var count = 4;

var counter = setInterval(timer, 1000);

function timer() {
  count -= 1;
  if (count === 0) {
    g1change();
    clearInterval(counter);
  }

  document.getElementById("gamediv").innerHTML = '<center><p id="countdown">' + count + '</p></center>';
}

function g1change() {
  document.getElementById("gamediv").innerHTML = '<h1 id="g1text">Click the button to the right!</h1><div onclick="correct()" class="g1button"></div><div onclick="wrong()" class="g1button">g1button</div>'
}
<div class="gamediv" id="gamediv">
  <div onclick="timer()" class="start">
    <h1 class="starttext">Start!</h1>
  </div>
</div>

【问题讨论】:

  • g1change() 被调用,但脚本将继续执行 timer() 的其余部分;)

标签: javascript function innerhtml intervals


【解决方案1】:

函数g1change() 正在被调用。随着脚本的继续执行,div 的内容也在不断更新。

clearInterval()方法被调用后,要么使用else,要么需要中断函数调用。

但计时器仍会在加载时启动。

不要在页面加载时调用setInterval()。在这里,我创建了一个新函数,即callTimer(),它在按钮单击时被调用

var count = 4;
var counter;

function callTimer() {
  counter = setInterval(timer, 1000);
}

function timer() {
  count -= 1;
  if (count === 0) {
    g1change();
    clearInterval(counter);
    //Termite the function
    return;
  }

  document.getElementById("gamediv").innerHTML = '<center><p id="countdown">' + count + '</p></center>';
}

function g1change() {
  document.getElementById("gamediv").innerHTML = '<h1 id="g1text">Click the button to the right!</h1><div onclick="correct()" class="g1button"></div><div onclick="wrong()" class="g1button"></div>'
}
<div class="gamediv" id="gamediv">
  <div onclick="callTimer()" class="start">
    <h1 class="starttext">Start!</h1>
  </div>
</div>

【讨论】:

  • 谢谢,解决了我遇到的功能问题,但计时器仍然在加载时启动。
  • 我试过了,但如果我这样做,计时器不会停止。它从 0 变为 -1,依此类推。
  • 一开始是的,但是它会在加载时启动,如果我在本地执行,计时器不会停止。
【解决方案2】:

var count = 4;

var counter = setInterval(timer, 1000);

function timer() {
  count -= 1;
  //console.log(count);
  if (count === 0) {
    g1change();
   
  }else{
    document.getElementById("gamediv").innerHTML = '<center><p id="countdown">' + count + '</p></center>';
  }
}

function g1change() {
  document.getElementById("gamediv").innerHTML = '<h1 id="g1text">Click the button to the right!</h1><div onclick="correct()" class="g1button"></div><div onclick="wrong()" class="g1button">g1button</div>';
   clearInterval(counter);
}
<div class="gamediv" id="gamediv">
  <div onclick="timer()" class="start">
    <h1 class="starttext">Start!</h1>
  </div>
</div>

参考上面的代码,你犯了一些逻辑错误。

【讨论】:

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