--- title: document.write slug: Web/API/Document/write tags: - API - DOM - Document - write - 参考 - 方法 translation_of: Web/API/Document/write ---
Document.write() 方法将一个文本字符串写入一个由 {{domxref("document.open()")}} 打开的文档流(document stream)。
注意: 因为 document.write 需要向文档流中写入内容,所以,若在一个已关闭(例如,已完成加载)的文档上调用 document.write,就会自动调用 document.open,这将清空该文档的内容。
document.write(markup);
<html>
<head>
<meta charset="UTF-8">
<title><code>document.write()</code> example</title>
<script>
function newContent() {
document.open();
document.write("<h1>Out with the old - in with the new!</h1>");
document.close();
}
</script>
</head>
<body onload="newContent();">
<p>Some original document content.</p>
</body>
</html>
{{EmbedLiveSample("Syntax")}}
向一个已经加载,并且没有调用过 {{domxref("document.open()")}} 的文档写入数据时,会自动调用 document.open。一旦完成了数据写入,建议调用 {{domxref("document.close()")}},以告诉浏览器当前页面已经加载完毕。写入的数据会被解析到文档结构模型(DOM)里。在上面的例子里,元素 h1 会成为文档中的一个节点。
如果 document.write() 调用发生在 HTML 里的 <script> 标签中,那么它将不会自动调用 document.open()。详见如下例子:
<script>
document.write("<h1>Main title</h1>")
</script>
document.write 和 {{domxref("document.writeln")}} 在 XHTML 文档中不可用(控制台上会显示 "Operation is not supported"[NS_ERROR_DOM_NOT_SUPPORTED_ERR] 的报错信息)。 当打开本地的 .xhtml 格式的文件或任何其他 {{Glossary("MIME type", "MIME 类型")}}为 application/xhtml+xml 的文档时,均会报错。更多信息可查看 W3C XHTML FAQ。document.write 会被忽略,控制台会显示 "A call to document.write() from an asynchronously-loaded external script was ignored" 的报错信息。document.write 多于一次时会引发错误 SCRIPT70: Permission denied。document.write() 注入的<script>,以防止使用 2G 连接的用户找不到 HTTP 缓存。前往此链接查看这种情况发生需要满足的条件。| 规范 | 状态 | 备注 |
|---|---|---|
| {{SpecName("HTML WHATWG", "#dom-document-write", "document.write(...)")}} | {{Spec2("HTML WHATWG")}} | |
| {{SpecName("DOM2 HTML", "html.html#ID-75233634", "document.write(...)")}} | {{Spec2("DOM2 HTML")}} |
{{Compat("api.Document.write")}}