[英]odd Javascript setTimeout behaviour
以下代碼等待2秒鍾,然后顯示一些hello world。
<!DOCTYPE html>
<html>
<body onload="myTimedFunction()">
<script>
function myTimedFunction() {
setTimeout(function() { document.write("hello world");document.write(" hello world2");runMe();}, 2000);
}
function runMe(){document.write(" hello world3");}
</script>
<br>
<p>This text will disappear when the script runs</p>
</body>
</html>
就像在p標簽中說的那樣,腳本運行后,文本消失。 此外,腳本運行時,網頁上會顯示“正在連接...”並在其旁邊顯示一個加載符號; 當我逃脫時,這消失了。 為什么文字消失了? 為什么直到我遇到逃脫,缺少分號的JavaScript才會停止? 我使用的是Firefox,在Chrome中,“連接中...”從不出現,但是文本仍然消失。 感謝您的閱讀。
如果當前文檔仍處於“打開”狀態,即仍在解析中,則document.write
將其參數字符串插入document.write
中的當前位置。 但是,當頁面完成解析后(就像在onload
之后(以及兩秒鍾的超時))一樣,它將關閉; document.write
將重新打開它,從而刪除所有當前內容。
創建一個文本節點,然后將其附加到<body>
!
function myTimedFunction() {
setTimeout(function () {
var textNode = document.createTextNode('hello world');
document.body.appendChild(textNode);
}, 2000);
}
此問題與setTimeout沒有任何關系。 這通常在使用document.write時發生。
只需將您的document.write替換為:
document.querySelector('body>p').innerHTML += 'hello world';
如果您查找它,將會發現document.write被認為是一種不好的做法,請出於某些原因檢查此帖子 ,但在您的情況下,主要原因是:
頁面加載完成后執行的document.write將覆蓋頁面,或寫入新頁面,或不起作用
您可以嘗試以下代碼:
<!DOCTYPE html>
<html>
<body onload="myTimedFunction()">
<br>
<p>This text will disappear when the script runs</p>
</body>
</html>
<script>
function myTimedFunction() {
setTimeout(function() { document.write(document.body.innerHTML+"hello world");document.write(" hello world2");runMe();}, 2000);
}
function runMe(){document.write(" hello world3");}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.