简体   繁体   English

object.innerHTML无法正确更新?

[英]object.innerHTML not updating properly?

I tried to make a progress bar in javascript, but it didnt load till my program was finished. 我试图用javascript制作进度条,但直到程序完成后才加载。 How can i make it updating while the program is still running? 在程序仍在运行时如何进行更新?

 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="main" onclick="my()">1</div> <button onclick="myFunction()">start</button> <script> function myFunction() { for(var i=0;i<1000000;i++){ document.getElementById("main").innerHTML=i; } } </script> </body> </html> 

Use setInterval method which runs in the background without blocking. 使用setInterval方法,该方法在后台运行而不会阻塞。 Once reached the condition you can clear the interval using clearInterval method. 达到条件后,您可以使用clearInterval方法清除间隔。

function myFunction() {
  // get element reference and cache in a variable
  let main = document.getElementById("main"),
    // initialize i as 0
    i = 0;
  // keep interval reference for clearing once i reached 1000000
  let intrvl = setInterval(() => {
    // check value of i and increment, if reached 1000000 clear the interval
    if (i++ === 1000000) clearInterval(intrvl);
    // update the content of main element
    main.innerHTML = i;
  }, 1000); // set required delay in millisecond, any value lesser than 10 will be automatically converts to 10
}

 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="main" onclick="my()">1</div> <button onclick="myFunction()">start</button> <script> function myFunction() { let main = document.getElementById("main"), i = 0; let intrvl = setInterval(() => { if (i++ === 1000000) clearInterval(intrvl); main.innerHTML = i; },1000); } </script> </body> </html> 

I used setInterval instead of for cicle and i used parseInt() to get integer value of your div innerHTML and then increment it 我用setInterval代替cicle,我用parseInt()来获取div innerHTML的整数值,然后递增它

setInterval(myFunction, 1000) runs myFunction() every 1000 milliseconds setInterval(myFunction, 1000) myFunction()每1000毫秒运行一次myFunction()

 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="main" onclick="my()">1</div> <button onclick="setInterval(myFunction, 1000)">start</button> <script> function myFunction(){ var value = parseInt(document.getElementById("main").innerHTML); document.getElementById("main").innerHTML=value+1; } </script> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM