From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../createhtmldocument/index.html | 92 ++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 files/zh-cn/web/api/domimplementation/createhtmldocument/index.html (limited to 'files/zh-cn/web/api/domimplementation/createhtmldocument') diff --git a/files/zh-cn/web/api/domimplementation/createhtmldocument/index.html b/files/zh-cn/web/api/domimplementation/createhtmldocument/index.html new file mode 100644 index 0000000000..558f4bad6c --- /dev/null +++ b/files/zh-cn/web/api/domimplementation/createhtmldocument/index.html @@ -0,0 +1,92 @@ +--- +title: DOMImplementation.createHTMLDocument +slug: Web/API/DOMImplementation/createHTMLDocument +translation_of: Web/API/DOMImplementation/createHTMLDocument +--- +

{{ApiRef("DOM")}}{{SeeCompatTable}}

+ +

概述

+ +

该方法 (属于document.implementation) 用来创建一个新的HTML文档.

+ +

语法

+ +
var doc = document.implementation.createHTMLDocument(title);
+
+ + + +

例子

+ +

下面的例子演示如何创建了一个新的HTML文档,并把它插入到当前文档的一个{{ HTMLElement("iframe") }}中.

+ +

查看在线演示

+ +

例子中的HTML代码如下:

+ +
<body>
+  <p>Click <a href="javascript:makeDocument()">here</a> to create a new document and insert it below.</p>
+  <iframe id="theFrame" src="about:blank" />
+</body>
+
+ +

例子中用JavaScript实现的makeDocument()方法如下:

+ +
function makeDocument() {
+  var frame = document.getElementById("theFrame");
+
+  var doc = document.implementation.createHTMLDocument("New Document");
+  var p = doc.createElement("p");
+  p.innerHTML = "This is a new paragraph.";
+
+  try {
+    doc.body.appendChild(p);
+  } catch(e) {
+    console.log(e);
+  }
+
+  // 将新建的HTML文档放到iframe中.
+
+  var destDocument = frame.contentDocument;
+  var srcNode = doc.documentElement;
+  var newNode = destDocument.importNode(srcNode, true);
+
+  destDocument.replaceChild(newNode, destDocument.documentElement);
+}
+
+ +

代码 4-12 行创建了一个新的HTML文档,并在里面插入一些内容. 第4行 createHTMLDocument()构造了一个标题为"New Document"的HTML文档. 5-6行创建了一个段落元素并在里面插入了一些内容, 8-12行将新建的段落元素插入到HTML文档中.

+ +

16行获取了iframe的contentDocument 属性.这是我们将要插入新建的HTML文档的地方. 下面的两行将新建的HTML文档插入到了iframe的根元素中.这样,我们用20行代码实现了用一个新建的HTML文档替换iframe中原有文档的目的.

+ +

备注

+ +

新生成的HTML文档有如下的初始结构:

+ +
<!doctype html>
+<html>
+<head>
+<title>title</title>
+</head>
+<body>
+</body>
+</html>
+
+ +

译者注:

+ +
alert(document.implementation.createHTMLDocument("myTitle").documentElement.outerHTML)
+
+//<html><head><title>myTitle</title></head><body></body></html>
+
+ +

规范

+ + + +

{{ languages( { "en": "en/DOM/DOMImplementation.createHTMLDocument" } ) }}

-- cgit v1.2.3-54-g00ecf