在函数的for循环内动态更改元素的内部文本

Change innertext of element dynamically inside for loop of a function

问题:输入更大的数字(如 10000)后,新段落元素的内部文本仅在 for 循环结束后才会更新。请帮助更新每个号码的内文。

在将数字作为输入发送到输入元素后发生 onchange 事件时调用增量函数。

JAVASCRIPT :

function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    for (g = 1; g < count; g++) {
        stat.innerText = Number(g + 1) + " out of " + count + " records have been processed";
    }
}

我并不是说这是一个好的解决方案,但这应该可以达到您想要的效果

function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    updateInnerText(0, count);
}

function updateInnerText(number, max){
    if(number < max){
        stat.innerText = Number(number + 1) + " out of " + count + " records have been processed";
        setTimeout(function(){
            updateInnerText(number+1, max);
        }, 500);
    }
}

DOM 在执行线程空闲之前不会重绘。您需要在代码中引入异步延迟才能看到渐进式更新。

function increment() {
  var count = document.getElementById('ac_count').value;
  var stat = document.createElement("p");
  stat.id = "current_status";
  document.body.appendChild(stat);

  var g = 1
  var itvl = setInterval(function() {
    update(g);
    g += Math.floor(Math.random() * 20) + 1
    if (g >= count) {
      clearInterval(itvl);
      update(count);
    }
  }, 10)

  function update(g) {
    stat.textContent = g + " out of " + count + " records have been processed";
  }
}
<input type=number value=10000 id=ac_count>
<button onclick="increment()">CLICK ME</button>