可能很多朋友都遇到過這樣的情況,那就是使用document.write()函數向網頁中寫內容的時候,會把文檔中的原來的內容給清空,這一點對于初學者來說算是一個困擾,下面就介紹一下為什么會出現這種情況,當然也就知道如何避免此種情況的發生了。
先看一段代碼實例:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>Document</title> <script type="text/javascript"> window.onload=function(){ document.write("重溫 JavaScript"); } </script> </head> <body> <div>Hello JavaScript</div> </body> </html>
從以上代碼的可以看出document.write()函數將原來的文檔內容清空了,下面介紹一下出現此種情況的原因:
window.onload事件是在文檔內容完全加載完畢再去執行事件處理函數,當然文檔流已經關閉了,這個時候執行doucment.writ()函數會自動調用document.open()函數創建一個新的文檔流,并寫入新的內容,再通過瀏覽器展現,這樣就會覆蓋原來的內容。不過很多朋友還有會這樣的疑問,為什么類似下面的情況,原來網頁中的內容不會被覆蓋,代碼如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>Document</title> <script type="text/javascript"> document.write("重溫 JavaScript"); </script> </head> <body> <div>Hello JavaScript</div> </body> </html>
在以上代碼中,原來的文檔內容并沒有被清空,這是因為當前文檔流是由瀏覽器所創建,并且document.wirte()函數身處其中,也就是執行此函數的時候文檔流并沒有被關閉,這個時候不會調用document.open()函數創建新文檔流,所以也就不會被覆蓋了??赡苓€有朋友會問為什么下面的方式還是不行,代碼如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>Document</title> <script type="text/javascript"> document.close(); document.write("重溫 JavaScript"); </script> </head> <body> <div>Hello JavaScript</div> </body> </html>
上面使用document.close()關閉文檔流了,為什么還是不能夠覆蓋原來的內容的,很遺憾,文檔流是由瀏覽器創建,無權限手動關閉,document.close()函數只能夠關閉由document.open()函數創建的文檔流??聪旅娴拇a實例:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>Document</title> <script type="text/javascript"> function create(){ var newWindow=window.open("","Document","_blank"); newWindow.document.write("Hello JavaScript"); newWindow.document.close(); newWindow.document.write("覆蓋后的輸出"); } window.onload=function(){ var obt=document.getElementById("bt"); obt.onclick=function(){ create(); } } </script> </head> <body> <div id="print">Hello JavaScript</div> <input type="button" id="bt" value="查看效果"/> </body> </html>
由doucment.open()創建的文檔流就可以由document.close()關閉,那么第二個document.write()輸出的內容會覆蓋掉第一個輸出的內容。
異步引用外部JavaScript時,必須先運行document.open()清空文檔,然后才能運行document.write(),參數寫在body內容的開頭。
如果不先運行document.open(),直接運行document.write(),則無效且Chrome有如下提示:
// asyncWrite.jsdocument.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()也能寫入含有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>
總結
以上所述是小編給大家介紹的JS 中document.write()的用法和清空的原因淺析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答