javascript document.write() 有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13741584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does document.write() do?
提问by Akhil Sekharan
This is a very basic question. I have this script:
这是一个非常基本的问题。我有这个脚本:
<script type="text/javascript">
function write(){
document.write('Hello2')
}
write();
</script>
It shows my complete page. And at the end of page Hello2will be displayed. But when ever I go to developer tools and call write(), it will replace my entire body html. Just curious to know.
它显示了我的完整页面。并在页面的末尾显示Hello2。但是当我去开发人员工具并调用write() 时,它会替换我的整个身体 html。只是好奇想知道。
window.onload=write;// has the same effect. Clear's my page.
Thanks.
谢谢。
回答by T.J. Crowder
When the document is being read and parsed by the browser, if there's a script
element that calls document.write
, the output of document.write
is inserted into the document at that point. Later, though, once the page is fully loaded, if you use document.write
, it implicitly performs a document.open
, which wipes out the page and starts writing a new one from scratch.
当浏览器正在读取和解析文档时,如果有一个script
元素调用document.write
,则document.write
在该点将的输出插入到文档中。但是,稍后,一旦页面完全加载,如果您使用document.write
,它会隐式执行 a document.open
,这会清除页面并从头开始编写一个新页面。
More on MDN:
更多关于 MDN:
In general, rather than using document.write
to add content to a page, use the various DOM methods(either directly, or via a library like jQuery, YUI, Closure, or any of several others).
一般来说,不要使用document.write
向页面添加内容,而是使用各种DOM 方法(直接使用,或通过jQuery、YUI、Closure或其他几个库中的任何一个)。
回答by Chamila Chulatunga
When it is executed afterthe page has completed loading, it overwrites the entire content - one of the points raised in the answer to this question: Why is document.write considered a "bad practice"?
在页面完成加载后执行时,它会覆盖整个内容 - 这个问题的答案中提出的观点之一:为什么 document.write 被认为是“不良做法”?
回答by Maddy
document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
document.write 写入文档流,在关闭(加载)的文档上调用 document.write 会自动调用 document.open,这将清除文档。