bug收集:專門解決與收集bug的網站
網址:www.bugshouji.com
今日分享小知識
document.write會不會覆蓋頁面內容
先看看示例代碼,再看 write 的介紹
首先,直接來看看下面的示例,判斷 document.write 是否會覆蓋頁面上的內容
示例一:
<div> 原來網頁內容</div><script type="text/javascript"> document.write("新的內容");</script>示例二:
<div> 原來網頁內容</div><script type="text/javascript"> window.onload=function (){ document.write("新的內容"); }</script>示例三:
<div> 原來網頁內容</div><button type="button" id="btnAddContent">添加</button><script type="text/javascript"> var btn = document.getElementById("btnAddContent"); btn.onclick=function (){ document.write("新的內容"); }</script>結果:
示例一,不覆蓋
示例二,會覆蓋
示例三,會覆蓋
Document.write() 方法將一個文本字符串寫入一個由 document.open() 打開的文檔流(document stream)
注意: 因為 document.write 需要向文檔流中寫入內容,所以,若在一個已關閉(例如,已完成加載)的文檔上調用 document.write,就會自動調用 document.open,這將清空該文檔的內容,在document.open方法會有具體解釋。
Document.open() 方法打開一個要寫入的文檔。
這將會有一些連帶的影響。例如:
在頁面加載完成後(會自動關閉文檔 —— document.close()),而 onload 與 onclick 事件在調用時,頁面均已加完成,所以,調用 document.write 時,會先調用 document.open 方法,而 open 方法會把文檔中的所有結點清除,這就是 document.write 使頁面內容被覆蓋的原因
大家好,從2月開始,將每天更新公眾號,歡迎大家閱讀;也可以私信我,你想看的內容