首頁 > web前端 > js教程 > 主體

為什麼 document.write() 會清除頁面?

Susan Sarandon
發布: 2024-10-24 06:59:30
原創
751 人瀏覽過

Why Does document.write() Clear the Page?

為什麼 Document.write 會清空頁面?

在JavaScript 中使用document.write() 方法時,程式設計師經常會遇到一個奇特的情況行為:在事件處理程序(例如onClick)中呼叫document.write() 可能會導致文檔被清除。

要理解這種意外結果,必須掌握 document.write() 的本質。此函數寫入文件流,文檔流是表示瀏覽器中顯示的文檔的連續資料流。

在提供的程式碼範例中:

<code class="html"><form name="myForm">
    <input type="checkbox" name="thebox" />
    <input type="button" onClick="validator()" name="validation" value="Press me for validation" />
</form>

<script type="text/javascript">
    function validator() {
        if (document.myForm.thebox.checked) {
            document.write("checkBox is checked");
        } else {
            document.write("checkBox is NOT checked");
        }
    }
</script></code>
登入後複製

validator() 函數點擊「驗證」按鈕時觸發。發生的情況如下:

  1. 此時,文件可能已完成加載,這表示文件流已關閉。
  2. 呼叫 document.write() 自動觸發 document.open( ),這會清除目前文檔,刪除所有現有元素。
  3. 隨後,在 document.write() 中指定的文字將呈現在現在為空的文檔中。

因此,表單元素(複選框和按鈕)從頁面中刪除,因為整個文件被刷新,用 document.write() 的輸出替換先前的內容。

因此,在使用 document.write() 時,在寫入文件流之前明確使用 document.open() 確保文件流保持開啟狀態至關重要。否則,清除文件的不可預測的行為可能會破壞預期的功能。

以上是為什麼 document.write() 會清除頁面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!