document.write() 是 JavaScript 中用於向文件寫入內容的方法。但它有個非常重要的特性,若不理解可能導致意料之外的結果。本文將詳細說明。
請記住,在頁面載入之後,瀏覽器的輸出流會自動關閉。此後,任何對當前頁面進行操作的 document.write() 方法將開啟一個新的輸出流,並清除當前頁面內容(包括源文件中的任何變數或值)。因此,若希望用腳本生成的 HTML 替換當前頁面,就必須把 HTML 內容連接起來賦給一個變數,再用一次 document.write() 完成寫入,而不必清除文件並開啟新資料流。
另外要注意相關方法 document.close()。腳本向視窗寫完內容後,必須關閉輸出流。在延時腳本的最後一個 document.write() 後面,必須確保含有 document.close(),否則圖片與表單將無法顯示;而且後續呼叫的 document.write() 只會把內容附加到頁面後,而不會清除現有內容。
建立一個按鈕,為文件組合新的 HTML 內容,包括新標題與背景顏色。範例中使用了 += 運算子,把右側字串附加到左側變數中,方便把多個語句組合成長字串:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<title>Writing to Same Doc</title>
<script language="JavaScript">
function reWrite(){
// 為新視窗組裝內容
var newContent = "<html><head><title>A New Doc</title></head>"
newContent += "<body bgcolor='aqua'><h1>This document is brand new.</h1>"
newContent += "Click the Back button to see original document."
newContent += "</body></html>"
// 將 HTML 寫入文件
document.write(newContent)
document.close() // 關閉輸出流
}
</script>
</head>
<body>
<form>
<input type="button" value="Replace Content" onClick="reWrite()">
</form>
</body>
</html>
載入文件並點擊按鈕後,你會注意到瀏覽器標題欄的文件標題隨之改變。再次點擊時,動態寫入的第二個頁面載入速度甚至比重新載入原始文件還快。
這種情況稍複雜,因為腳本建立了一個子視窗,整個生成的文件都寫入該視窗。為了讓新視窗的參照在兩個函數間保持有效,我們把 newWindow 宣告為全域變數。頁面載入時,onLoad 事件呼叫 makeNewWindow() 建立一個空的子視窗:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<title>Writing to Subwindow</title>
<script language="JavaScript">
var newWindow
function makeNewWindow(){
newWindow = window.open("","","status,height=200,width=300")
}
function subWrite(){
// 若子視窗被關閉則重新開啟
if(newWindow.closed){
makeNewWindow()
}
// 將子視窗移到前台
newWindow.focus()
// 為新視窗組裝內容
var newContent = "<html><head><title>A New Doc</title></head>"
newContent += "<body bgcolor='coral'><h1>This document is brand new.</h1>"
newContent += "</body></html>"
// 將 HTML 寫入新視窗
newWindow.document.write(newContent)
newWindow.document.close() // 關閉輸出流
}
</script>
</head>
<body onLoad="makeNewWindow()">
<form>
<input type="button" value="Write to Subwindow" onClick="subWrite()">
</form>
</body>
</html>
頁面上的按鈕呼叫 subWrite(),它會先檢查子視窗的 closed 屬性;若使用者手動關閉了視窗,便重新開啟。要特別注意的是,write() 與 close() 都明確指定了子視窗,這與範例一直接操作當前文件有著關鍵區別。