document.write resets body once

断了今生、忘了曾经 提交于 2019-12-10 20:17:20

问题


When I used document.write after loading the body (via onclick event), it overwrites the entire body. I want this for what I'm trying to achieve. However, when I do it again, it simply adds on to the previous content. Why does it overwrite everything the first time and only add on the next?


回答1:


If the document isn't open for writing, then calling document.write will automatically call document.open.

The first time you call document.write, the browser has loaded the document and thus closed it for writing. This calls document.open which wipes out the existing document and creates a new one to write into.

Since the browser isn't loading this, it doesn't automatically close it for writing, so the content is appended when you call docment.write again. You can explicitly call document.close and document.open if you want to wipe out the content.

See https://developer.mozilla.org/en/document.write for more details.




回答2:


When you use document.write, it writes directly to the page/body. If you want to write to some specific element, you can use syntax such as this:

document.getElementById('elementID').innerHTML = 'your string';


来源:https://stackoverflow.com/questions/4511886/document-write-resets-body-once

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