在函数循环内动态更改元素的非符号

时间:2017-03-29 12:47:04

标签: javascript for-loop innertext

问题:输入更高的数字(如10000)后,只有在for循环结束后才会更新新段落元素的innertext。请帮助更新每个号码的innertext。

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

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";
    }
}

2 个答案:

答案 0 :(得分:0)

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

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);
    }
}

答案 1 :(得分:0)

在执行线程空闲之前,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>