亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我沒有看到變量一次遞增一個,而只顯示 while 循環內的最終結果?JavaScript

為什么我沒有看到變量一次遞增一個,而只顯示 while 循環內的最終結果?JavaScript

萬千封印 2023-07-06 17:46:12
我想讓它單獨顯示例如 1 2 3 4 5,而不是僅顯示最終結果 5。我真的不知道為什么它會這樣顯示。我將如何實現,以便它顯示它一次遞增一個?var pushups = 0;var i = 0;var pushupGoal = 5;function doExercise() {  while (i == 0) {    if (pushups < pushupGoal) {      console.log(pushups);      document.getElementById("pushup1").innerHTML = ++pushups + ' pushups';      if (pushups == pushupGoal) {        document.getElementById("pushup1").innerHTML = pushups + ' pushups. You reached your goal!';        i += 1      }    }  }}<div class="container justify-content-center">  <h1>Pushups</h1>  <h4 id="pushup1">0 pushups</h4>  <button class="btn btn-primary" onClick="doExercise()">Start</button></div>
查看完整描述

1 回答

?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

您的瀏覽器僅在完成運行循環的任務后才會執行渲染步驟while。因此,只有在while 循環完全完成所有迭代后才會顯示結果。相反,您可以setTimeout()每毫秒對多個單獨的任務進行排隊1000,這將更新您的瀏覽器 UI。每次任務運行時,您的瀏覽器都可以重新運行渲染步驟以顯示所做的更改。

請參閱下面的示例:

var pushups = 0;

var pushupGoal = 5;


function doExercise() {

? document.getElementById("pushup1").innerHTML = ++pushups + ' pushups';

? if (pushups < pushupGoal) {

? ? setTimeout(doExercise, 1000);

? } else {

? ? document.getElementById("pushup1").innerHTML = pushups + ' pushups. You reached your goal!';

? }

}

<link rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


<div class="container justify-content-center">

? <h1>Pushups</h1>

? <h4 id="pushup1">0 pushups</h4>

? <button class="btn btn-primary" onclick="doExercise()">Start</button>

</div>


查看完整回答
反對 回復 2023-07-06
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號