全面理解document.write()

W3C 標準

WHATWG: write()javascript

定義和用法

文檔節點的write()方法用於寫入文檔內容,能夠傳多個參數,寫入的字符串會按HTML解析。html

  • 語法:document.write()java

  • 參數:字符串,能夠傳多個字符串參數web

  • 返回值:undefinedsegmentfault

注意事項

  1. 若是document.write()在DOMContentLoaded或load事件的回調函數中,當文檔加載完成,
    則會先清空文檔(自動調用document.open()),再把參數寫入body內容的開頭。dom

  2. 在異步引入的js和DOMContentLoaded或load事件的回調函數中運行document.write(),
    運行完後,最好手動關閉文檔寫入(document.close())。異步

示例代碼

在head中運行document.write(),則參數寫在body內容的開頭。async

<!-- 運行前 -->
<head>
    <script>
        document.write('<p>test</p>');
    </script>
</head>
<body>
    <h2>write()</h2>
</body>

<!-- 運行後 -->
<head>
    <script>
        document.write('<p>test</p>');
    </script>
</head>
<body>
    <p>test</p>
    <h2>write()</h2>
</body>

在body中運行document.write(),則參數寫在運行的script標籤後面函數

<!-- 運行前 -->
<div>
    <script>
        document.write('<p>test</p>');
    </script>
    <p>content</p>
</div>

<!-- 運行後 -->
<div>
    <script>
        document.write('<p>test</p>');
    </script>
    <p>test</p>
    <p>content</p>
</div>

同步引用外部js,參數也是寫在運行的script標籤後面spa

// syncWrite.js
document.write('<p>test</p>');
<!-- syncWrite.html -->
<!-- 運行前 -->
<body>
    <script src="syncWrite.js"></script>
    <p>content</p>
</body>

<!-- 運行後 -->
<body>
    <script src="syncWrite.js"></script>
    <p>test</p>
    <p>content</p>
</body>

異步引用外部js,必須先運行document.open()清空文檔,而後才能運行document.write(),參數寫在body內容的開頭。
若是不先運行document.open(),直接運行document.write(),則無效且Chrome有以下提示:

圖片描述

// asyncWrite.js
document.open();
document.write('<p>test</p>');
document.close();
<!-- asyncWrite.html -->
<!-- 運行前 -->
<body>
    <script src="asyncWrite.js" async></script>
</body>

<!-- 運行後 -->
<body>
    <p>test</p>
</body>

若是document.write()在DOMContentLoaded或load事件的回調函數中,則不論是在head中,body中,同步的js中,異步的js中,
都會先清空文檔(自動調用document.open()),而後運行document.write(),參數寫在body內容的開頭

<!-- 運行前 -->
<body>
    <script>
        window.addEventListener('load', function () {
            document.write('<p>test</p>');
            document.close();
        }, false);
    </script>
</body>

<!-- 運行後 -->
<body>
    <p>test</p>
</body>

document.write()也能寫入含有script標籤的字符串,可是須要轉義。寫入的script標籤中的內容會正常運行。

<!-- 運行前 -->
<script>
    document.write('<script>document.write("<p>test</p>");<\/script>');
</script>

<!-- 運行後 -->
<script>
    document.write('<script>document.write("<p>test</p>");<\/script>');
</script>
<script>document.write("<p>test</p>");</script>
<p>test</p>

document.write()能夠傳入多個參數。

<!-- 運行前 -->
<body>
    <script>
        document.write('<h2>multiArgument</h2>','<p>test</p>');
    </script>
</body>

<!-- 運行後 -->
<body>
    <script>
        document.write('<h2>multiArgument</h2>','<p>test</p>');
    </script>
    <h2>multiArgument</h2>
    <p>test</p>
</body>

參考資料

  1. https://segmentfault.com/a/11...

  2. http://web.jobbole.com/83288/

  3. https://developer.mozilla.org...

相關文章
相關標籤/搜索