开发者

javascript - document.write error?

Consider the script..

<html>
<head>
   <script type="text/javascript">
        document.write('TEST');
   </script>
</head>

<body>
    Some body content ...
</body>

</html>

This works fine and the word 'TEST' is added to the <body>

But when

<sc开发者_如何学编程ript type="text/javascript">
    window.onload = function(){
        document.write('TEST');
    }
</script>

is used, then the body content is fully replaced by the word 'TEST' i.e, the old body contents are removed and ONLY the word 'TEST' is added.

This happens only when document.write is called within window.onload function

I tried this in chrome. Is there any mistake made by me ? any suggestions ?


document.write() is unstable if you use it after the document has finished being parsed and is closed. The behaviour is unpredictable cross-browser and you should not use it at all. Manipulate the DOM using innerHTML or createElement/createTextNode instead.

From the Mozilla documentation:

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. The text you write is parsed into the document's structure model. In the example above, the h1 element becomes a node in the document.

If the document.write() call is embedded directly in the HTML code, then it will not call document.open().

The equivalent DOM code would be:

window.onload = function(){
    var tNode = document.createTextNode("TEST");
    document.body.appendChild(tNode);
}


  1. in the first case the word is not written in the body .. it is written in the head
  2. the first one works because the document is still open for writting.. once it has completed (DOM loaded) the document is closed, and by attempting to write to it you replace it ..


When document is full loaded, any further call to document.write() will override document content. You must use document.close() before calling document.write() to avoid overwriting.


First create an element, for example a div, than add content to the div with window.onload event.

document.write('<div id="afterpostcontent"><\/div>');
window.onload = function()
{
    document.getElementById('afterpostcontent').innerHTML = '<span>TEST<\/span>';
}

You can create an external JavaScript file with this content and just call it anywhere, for example:

<script src="afterpostcontentcode.js"></script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜