From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/document/write/index.html | 111 ++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 files/zh-cn/web/api/document/write/index.html (limited to 'files/zh-cn/web/api/document/write') diff --git a/files/zh-cn/web/api/document/write/index.html b/files/zh-cn/web/api/document/write/index.html new file mode 100644 index 0000000000..2a9b18e9e1 --- /dev/null +++ b/files/zh-cn/web/api/document/write/index.html @@ -0,0 +1,111 @@ +--- +title: document.write +slug: Web/API/Document/write +tags: + - API + - DOM + - Document + - write + - 参考 + - 方法 +translation_of: Web/API/Document/write +--- +
{{ApiRef("DOM")}}
+ +

Document.write() 方法将一个文本字符串写入一个由 {{domxref("document.open()")}} 打开的文档流(document stream)。

+ +
+

注意: 因为 document.write 需要向文档中写入内容,所以,若在一个已关闭(例如,已完成加载)的文档上调用 document.write,就会自动调用 document.open这将清空该文档的内容

+
+ +

语法

+ +
document.write(markup);
+ +

参数

+ +
+
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
+ +
注意:在有deferred 或 asynchronous 属性的 script 中,document.write 会被忽略,控制台会显示 "A call to document.write() from an asynchronously-loaded external script was ignored" 的报错信息。
+ +
注意:在 Edge 中,在 {{HTMLElement("iframe")}} 内部调用 document.write 多于一次时会引发错误 SCRIPT70: Permission denied。
+ +
注意:从 Chrome 55 开始,Chrome(可能)不会运行通过 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")}}

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf