Document.write() - Web APIs 编辑

The Document.write() method writes a string of text to a document stream opened by document.open().

Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document.

Syntax

document.write(markup);

Parameters

markup
A string containing the text to be written to the document.

Example

<html>

<head>
  <title>Write 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>

Notes

The text you write is parsed into the document's structure model. In the example above, the h1 element becomes a node in the document.

Writing to a document that has already loaded without calling document.open() will automatically call document.open(). After writing, call document.close() to tell the browser to finish loading the page.

If the document.write() call is embedded within an inline HTML <script> tag, then it will not call document.open(). For example:

<script>
  document.write("<h1>Main title</h1>")
</script>
Note: document.write() and document.writeln do not work in XHTML documents (you'll get an "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] error in the error console). This happens when opening a local file with the .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ. Note: Using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "A call to document.write() from an asynchronously-loaded external script was ignored" in the error console. Note: In Edge only, calling document.write() more than once in an <iframe> causes the error "SCRIPT70: Permission denied". Note: Starting with version 55, Chrome will not execute <script> elements injected via document.write() when specific conditions are met. For more information, refer to Intervening against document.write().

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'document.write(...)' in that specification.
Living Standard
Document Object Model (DOM) Level 2 HTML Specification
The definition of 'document.write(...)' in that specification.
Obsolete

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:96 次

字数:5640

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文