gpt4 book ai didi

javascript - 如何使用间隔和函数来改变div的innerHTML?

转载 作者:行者123 更新时间:2023-12-03 00:53:25 25 4
gpt4 key购买 nike

所以我希望 div("gamediv") 的 innerHTML 在计时器达到 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()。随着脚本继续执行,div 的内容正在更新。

您可以使用 else 或需要在调用 clearInterval() 方法后中断函数调用。

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

不要在页面加载时调用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>

关于javascript - 如何使用间隔和函数来改变div的innerHTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com