您好我如何在div中显示javascript结果。代码是:
<script type='text/javascript'>
COUNTER_START = 40
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
我想让它在这个div中显示coundown计数器
<div id="counter"></div>
谢谢:D
答案 0 :(得分:3)
您可以使用innerHTML
:
document.getElementById("counter").innerHTML = /* ... HTML string here ... */;
您可以稍微缩短该脚本:Live Example | Source
(function() {
var elm = document.getElementById('counter');
var counter = 40;
tick();
function tick() {
elm.innerHTML = String(counter);
--counter;
if (counter >= 0) {
setTimeout(tick, 1000); // <=== Note, a function ref, not a string
}
else {
elm = undefined; // Release it as we don't need it anymore
}
}
})();
我不确定段落元素的内容是什么,所以我没有包含它。如果要在counter
的开头添加body
元素(作为p
,而不是div
),那么只需更改
var elm = document.getElementById('counter');
到
var elm = document.createElement('p');
document.body.insertBefore(elm, document.body.firstChild);
甚至不需要id
。 Live Example | Source
答案 1 :(得分:0)
要更改div的内容,请使用
document.getElementById("counter").innerHTML="something";