简体   繁体   中英

How to display javascript results in a div

Hi how do i display the javascript results in a div. the code is :

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

i want it to display the coundown counter in this div

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

Thank you :D

You can use innerHTML for that:

document.getElementById("counter").innerHTML = /* ... HTML string here ... */;

You can shorten that script a fair bit: 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
        }
    }

})();

I wasn't sure what the stuff with the paragraph element was, so I didn't include that. If it was meant to add the counter element at the beginning of the body (as a p , not a div ), then just change

var elm = document.getElementById('counter');

to

var elm = document.createElement('p');
document.body.insertBefore(elm, document.body.firstChild);

Doesn't even need the id . Live Example | Source

要更改div的内容,请使用

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM