[英]h1 element text is not changing using javascript but changes in console
我正在學習 web 開發,我正在嘗試在 javascript 中做最簡單的事情來了解它是如何工作的。 我有這個問題,頁面上的 h1 文本沒有改變,但是當我打開控制台時,它每次都會打印更改的值,這是代碼(提示,sleep() function 來自互聯網,我什么都不知道然而關於它,但它有效):
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
let counter = 0;
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function change(){
while(true)
{
document.querySelector("#show").innerText = counter;
counter++
console.log(document.querySelector("#show").innerText);
sleep(1000);
}
}
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TEST</title> <script> function change() { let counter = 0; setInterval(() => { document.querySelector("#show").innerText = counter; counter++; }, 1000); } </script> </head> <body> <button onclick="change()" id="button" >COUNT</button> <h1 id="show">0</h1> </body> </html>
嘗試使用 setInterval 更改您的更改 function。 您可以使用https://www.w3schools.com/jsref/met_win_setinterval.asp找到如何使用設置間隔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.