setinterval not able to run document.writeln

左心房为你撑大大i 提交于 2019-12-08 11:52:25

问题


Greetings,

The code below works for alert but doesn't for document.writeln. Is it because of the onload event? If so shouldn't the browser be able to add more elements after it's finished loading? - Trying to understand how it works (I am studying jquery in the meantime).

<body onload="timeMsg()">
<script type="text/javascript">
        function timeMsg()
        {
        var t=self.setInterval("randInt()",3000);
        }
        function randInt()
        { 
        document.writeln("<br />" +Math.floor(Math.random() * 7)); //doesn't work
        alert(Math.floor(Math.random() * 7));  //works

        }
    </script>
</body>

回答1:


An alternative

<body onload="timeMsg()">

<div id="outputDiv"></div>

<script type="text/javascript">
    function timeMsg()
    {
        var t = self.setInterval("randInt()", 3000);
    }

    function randInt()
    { 
        document.getElementById("outputDiv").innerHTML += "<br />" + Math.floor(Math.random() * 7);
        alert(Math.floor(Math.random() * 7));  //works
    }
</script>




回答2:


Once the browser has finished reading a complete HTML page, the "document" is closed. Calling document.write() (or its friends) after that point will implicitly re-open the document and obliterate everything that's there.

Instead of that, you can use DOM manipulation APIs to update the page.




回答3:


It works in Chrome. Maybe you should follow MDC's advice:

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call. Once you have finished writing, it is recommended to call document.close(), to tell the browser to finish loading the page.

Edit: As @Pointy points out (nice sentence ;)), this will replace the whole content of the page.

And one more thing: document.write is not available in XHTML documents!

Conclusion: Don't use it.

You could achieve the same effect by e.g.

document.body.innerHTML += "<br />" + Math.floor(Math.random() * 7);

or

var div = document.createElement('div');
div.appendChild(document.createTextNode(Math.floor(Math.random() * 7)));

document.body.appendChild(div);



回答4:


Rather than writing to the document, inject elements into the DOM:

var el = document.body.appendChild(document.createElement("div"));
el.innerHTML = Math.floor(Math.random() * 7));


来源:https://stackoverflow.com/questions/5253603/setinterval-not-able-to-run-document-writeln

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!