15

是否有一般规则,何时应该使用document.write更改网站内容以及何时使用.innerHTML

到目前为止,我的规则是:

1)添加新内容document.write时使用

2)更改现有内容.innerHTML时使用

但我很困惑,因为有人告诉我,一方面这.innerHTML是一个奇怪的 Microsoft 标准,但另一方面我读到document.writeXHTML 中不允许这样做。

我应该使用哪些结构来使用 JavaScript 操作我的源代码?

4

4 回答 4

12

innerHTML可用于通过字符串修改来更改 DOM 的内容。因此,如果您想在所选元素的末尾添加带有一些文本的段落,您可以这样做

document.getElementById( 'some-id' ).innerHTML += '<p>here is some text</p>'

尽管我建议尽可能多地使用特定于 DOM 操作的 API(例如document.createElementdocument.createDocumentFragment<element>.appendChild等)。但这只是我的偏好。

我唯一一次看到适用的用法document.write是在HTML5 Boilerplate 中(看看它如何检查 jQuery 是否正确加载)。除此之外,我会远离它。

于 2012-04-10T08:11:58.023 回答
12

innerHTML并且document.write不是动态更改/插入内容的真正可比方法,因为它们的用法不同并且用于不同的目的。

document.write应该与特定的用例相关联。当页面已加载且 DOM准备就绪时,您将无法再使用该方法。这就是为什么通常最常用于条件语句中,您可以在其中使用它来同步加载外部 javascript 文件(javascript 库),包括<script>块(例如,当您从 CDN 中加载 jQuery 时HTML5 Boilerplate)。

当页面与application/xhtml+xmlmime 类型一起提供时,您所读到的有关此方法和 XHTML 的内容是正确的:来自w3.org

document.write(如 document.writeln)在 XHTML 文档中不起作用(您将在错误控制台上收到“不支持操作”(NS_ERROR_DOM_NOT_SUPPORTED_ERR)错误)。如果打开具有 .xhtml 文件扩展名的本地文件或使用 application/xhtml+xml MIME 类型提供的任何文档,就会出现这种情况

这些方法之间的另一个区别与插入节点有关:当您使用.innerHTML方法时,您可以选择在何处附加内容,而使用 document.write 插入节点始终是使用此方法的文档部分。

于 2012-04-10T08:11:27.223 回答
2

1) document.write() puts the contents directly to the browser where the user can see it.

this method writes HTML expressions or JavaScript code to a document.

The below example will just print ‘Hello World’ into the document

<html>
  <body>
    <script>
    document.write("Hello World!");
    </script>
  </body>
</html>

2) document.innerHTML changes the inner content of an element

It changes the existing content of an element

The below code will change the content of p tag

<html>
<body>
<p id="test" onclick="myFun()">Click me to change my HTML content or my inner HTML</p>
<script>
function myFun() {
  document.getElementById("test").innerHTML = "I'm replaced by exiesting element";
}
</script>
</body>
</html> 

you could use document.write() without any connected HTML, but if you already have HTML that you want to change, then document.innerHTML would be the obvious choice.

于 2019-03-01T06:33:19.140 回答
0

我同意上述评论。基本上:

  • document.write在页面加载时很有用,可以在浏览器构建文档对象模型时输出新的 HTML 标记或内容。该内容在嵌入 JavaScript 语句的位置精确输出。
  • .innerHTML可随时将新的 HTML 标记/内容作为字符串插入,并且无论何时/何地运行 JavaScript,都可以更轻松地将其定向到 DOM 中的特定元素。

一些额外的注释......

当从 body 元素之外的脚本调用 document.write 时,如果在页面加载时调用,它的输出将附加到 body 元素;但是一旦页面被加载,同一个 document.write 将覆盖整个文档对象模型,从而有效地擦除您的页面。这完全取决于 document.write 与页面加载的时间。

如果您使用 document.write 将新内容附加到 body 元素的末尾,则最好使用以下方法:

document.body.innerHTML += "A string of new content!";

它更安全一些。

于 2021-02-23T12:33:21.123 回答