当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - setTimeout() and getElementById() don't work together

问题描述:

I first did this:

<script>

function result2() {

document.write("...");

}

function result1() {

document.write("..");

setTimeout(result2, 1000);

}

document.write(".");

setTimeout(result1, 1000);

</script>

<div id="body"></div>

setTimeout() doesn't work at all ninety-nine times out of a hundred, so I was surprised to see it working, even if it glitched at the very end. But it didn't work like I used to want, so I re-wrote the script just a little bit to be something like that:

<script>

function result2() {

document.getElementById("body").innerHTML = "...";

}

function result1() {

document.getElementById("body").innerHTML = "..";

setTimeout(result2, 1000);

}

document.getElementById("body").innerHTML = ".";

setTimeout(result1, 1000);

</script>

<div id="body"></div>

But nothing happened at all, it just gave me a blank page... So I tried setInterval(), but here again, it didn't work. So please, help me, how can I solve this problem?

网友答案:

The problem is when the code is executed, the elements are not available in the DOM. You can use any one of the below solution

  1. Move the <script> at the end of <body so, when the code is run, the elements are available in the DOM
  2. Wrap the code that access DOM elements in DOMContentLoaded event callback

<script>
    function result2() {
        document.getElementById("body").innerHTML = "...";
    }

    function result1() {
        document.getElementById("body").innerHTML = "..";
        setInterval(result2, 1000);
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById("body").innerHTML = ".";
        setInterval(result1, 1000);
    });

</script>
<div id="body"></div>
网友答案:

Add your script at the end of body tag and it should work

function result2() {
   document.getElementById("body").innerHTML = "...";
    }

function result1() {
    document.getElementById("body").innerHTML = "..";
        setInterval(result2, 1000);
    }

 document.getElementById("body").innerHTML = ".";
    setInterval(result1, 1000);
<div id="body"></div>
分享给朋友:
您可能感兴趣的文章:
随机阅读: