繁体   English   中英

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

[英]Change innertext of element dynamically inside for loop of a function

问题:输入更高的数字(如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";
    }
}

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

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> 

暂无
暂无

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

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