HTML - DOM write() 方法



HTML DOM 的write() 方法允許你直接將 HTML 或 JavaScript 表示式寫入文件。但是,如果在文件完全載入後呼叫它,則會替換文件的全部內容。

由於其破壞性行為和潛在的效能問題,通常建議在現代 Web 開發中避免使用此方法。

語法

以下是 HTML DOM write() 方法的語法:

document.write(exp1, exp2,.....expN);

引數

此方法接受如下所示的單個引數:

引數 描述
(exp1, exp2,..expN) 它表示你想要寫入文件的多個表示式。這些表示式按其出現的順序顯示。

返回值

此方法不返回任何值。

示例 1:直接將文字寫入文件

以下示例演示了 HTML DOM write() 方法的用法:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM Document write() Method</title>
</head>
<body>
<button onclick="fun()">Click me</button>
<p id="type"></p>
<script>
   function fun() {
      document.write("Welcome to Tutorials Point..")
   }
</script>
</body>
</html>

示例 2:在新視窗中寫入文字

在以下示例中,將開啟一個新視窗,並將文字插入到文件中:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM document write() Method</title>
</head>
<body>
<button onclick="fun()">Click me</button>
<p id="type"></p>
<script>
   function fun() {
      let x = window.open()
      x.document.write("Welcome to Tutorials Point..")
   }
</script>
</body>
</html>    

示例 3:直接將 HTML 元素寫入 HTML 輸出

在以下示例中,<b> 標籤用於使文字加粗,<em> 標籤用於使文件中的文字傾斜:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM document write() Method</title>
</head>
<body>
<button onclick="fun()">Click me</button>
<p id="type"></p>
<script>
   function fun() {
      document.write("<b><em>Welcome to Tutorials Point.. </em></b>");
   }
</script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
write() 是 1 是 12 是 1 是 1 是 3
html_dom_document_reference.htm
廣告