setinterval not able to run [removed]ln

2019-06-10 10:34发布

问题:

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