文件:open() 方法

Document.open() 方法開啟一個文件以供 寫入

這會帶來一些副作用。例如:

  • 當前在文件、文件內的節點或文件的視窗上註冊的所有事件監聽器都會被移除。
  • 所有現有節點都會從文件中移除。

語法

js
open()

引數

無。

返回值

一個 Document 物件例項。

示例

以下簡單程式碼會開啟文件,並用多個不同的 HTML 片段替換其內容,然後再關閉它。

js
document.open();
document.write("<p>Hello world!</p>");
document.write("<p>I am a fish</p>");
document.write("<p>The number is 42</p>");
document.close();

注意

當頁面載入後呼叫 document.write() 時,會自動呼叫 document.open()

內容安全

此方法受與其它屬性相同的 同源策略 限制,如果這樣做會改變文件的源,則無效。

三引數 document.open()

有一個鮮為人知且很少使用的三引數版本的 document.open(),它是 Window.open() 的別名(請參閱其頁面獲取完整詳細資訊)。

例如,此呼叫會在新視窗中開啟 github.com,並將其 opener 設定為 null

js
document.open("https://www.github.com", "", "noopener=true");

二引數 document.open()

瀏覽器過去支援一個二引數的 document.open(),其簽名如下:

js
document.open(type, replace);

其中 type 指定了你正在寫入的資料的 MIME 型別(例如 text/html),如果設定了 replace(即字串 "replace"),則指定新文件的歷史記錄條目將替換當前正在寫入的文件的歷史記錄條目。

此形式現在已過時;它不會丟擲錯誤,而是直接轉發到 document.open()(即等同於不帶引數執行它)。歷史記錄替換行為現在始終發生。

規範

規範
HTML
# dom-document-open-dev

瀏覽器相容性

另見