javascript - document.write error?

本秂侑毒 提交于 2019-11-27 05:31:14

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