2017-03-29 13 views
0

문제점 : 10000과 같이 더 높은 숫자를 입력하면 for 루프가 끝난 후에 만 ​​새 단락 요소의 innertext가 업데이트됩니다. 각 번호에 대해 고유 텍스트를 업데이트하도록 도와주세요.함수의 for 루프 안에서 동적으로 요소의 내부 텍스트를 변경하십시오.

입력 요소에 숫자를 입력 한 후 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"; 
    } 
} 
+1

내 생각 엔 그 루프가 너무 실행 빨리 심지어 다른 번호를 통지하지 않는 것입니다. 그것을 보이게하려면'recursive' 함수와 함께'setTimeout'을 사용하여 속도를 늦추십시오. – stackoverfloweth

+0

10000과 같이 큰 숫자를 입력하면 "10000 개의 레코드 중 10000 개가 처리되었습니다"라는 텍스트가 표시되기까지 약 5 초가 걸립니다. for 루프에서 console.log를 사용할 때 "10000 개의 레코드 중 2 개가 처리되었습니다"라는 메시지가 표시됩니다. "10000 개의 레코드 중 9999 개가 처리되었습니다" – Vincent

답변

0

찾고있는 효과를 달성한다 실행 스레드는 자유 다. 점진적인 업데이트를 보려면 코드에 비동기 지연을 도입해야합니다.

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>

+0

환상적인 버디! 이것이 내가 원했던 것이다. 고마워요! – Vincent

0

나는이 좋은 해결책이 제시하고 있지 않다, 그러나 이것은 당신이 DOM 때까지 다시 그리기하지 않습니다

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