如何反复更新< div>的内容通过只使用JavaScript? [英] How to repeatedly update the contents of a <div> by only using JavaScript?
问题描述
此刻我想转换此代码,以便它不会在提示框中显示我的值。我需要它在专门的< div>
内重复更新我的值。这应该每秒发生一次,因此循环延迟1000ms。那么我该如何转换这段代码?
pre $
for(var i = 0; i> 10; i ++){
setInterval(alert(i),1000);
}
我需要在这里显示:
< div id =timer>< / div>
href =https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementById =nofollow> getElementById()
来获取元素。
请使用 innerHTML
设置文本内容。
不要使用 setInterval
在循环中(除非你的意思是),因为这会导致你给 setInterval
执行 n
每次超时次数
执行使用< a href =https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval =nofollow> clearInterval
在你不在时停止执行间隔e。
var el = document.getElementById(timer); var i = 0; var interval = setInterval(function(){el.innerHTML = i ++; if(i> 10){clearInterval(interval); }},1000);
< div id =计时器>< / div>
或者,使用 setTimeout
并避免 setInterval
和 clearInterval
。那么你可以简单地在超过最大计数的时候不要超时。
var el = document.getElementById(timer); var i = 0; function counter(){el.innerHTML = i ++; if(i <= 10){setTimeout(counter,1000); }} counter();
< div id =定时器>< / div>
At the moment I want to convert this code so that it doesn't show the value of i in prompt boxes. I need it to repeatedly update the value of i inside a dedicated <div>
. This should occur every second, hence the delay in the loop by 1000ms. How do I convert this code then?
for(var i = 0; i > 10; i++) {
setInterval(alert(i),1000);
}
I need it to show in here:
<div id="timer"></div>
Do use getElementById()
to get the element.
Do use innerHTML
to set the text content.
Don't use setInterval
in loops (unless you mean to) because that will cause the callback you give to the setInterval
to be executed n
number of times every timeout.
Do use clearInterval
to stop the interval from executing when you are done.
var el = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
el.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
}
}, 1000);
<div id="timer"></div>
Alternatively, use setTimeout
and avoid setInterval
and clearInterval
. Then you can simply not make a new timeout when you are above your maximum count.
var el = document.getElementById("timer");
var i = 0;
function counter() {
el.innerHTML = i++;
if (i <= 10) {
setTimeout(counter, 1000);
}
}
counter();
<div id="timer"></div>
这篇关于如何反复更新< div>的内容通过只使用JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!