2013-01-12 88 views
0

嗨我如何在div中顯示javascript結果。代碼:如何在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> 

我希望它顯示coundown計數器在這個div

<div id="counter"></div> 

謝謝:d

+1

IDS必須是唯一的 - 你不能有一個'div'和'p'使用id =計數器 – Dennis

回答

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); 

甚至不會需要idLive Example | Source

0

要改變DIV的內容,請使用

document.getElementById("counter").innerHTML="something";