Trouble outputting full list of numbers using innerHTML
-
25-09-2019 - |
문제
the following is code to create a sequential list of numbers from 1 to 10. I'd like to take this list and output in the div "pagination" using innerHTML. However, when I execute the script, the only thing that is outputted is the number 10. When I overwrite the page using document.write instead, it outputs the whole list. Can someone tell me what I'm doing wrong? Thanks.
function generateNumbers() {
var numbers = new Array();
// start generating numbers
for(var i = 1; i <= 10; i+= 1) {
numbers.push( i );
}
// print numbers out.
for(var i = 0; i < numbers.length; i++) {
document.getElementById("pagination").innerHTML = numbers[i] + "<br>";
}
}
and in the HTML:
<div id="pagination"></div>
해결책
Well, you override innerHTML
in every step.
Try:
document.getElementById("pagination").innerHTML += numbers[i] + "<br>";
Or better:
// no for loop
document.getElementById("pagination").innerHTML = numbers.join("<br>");
다른 팁
for(var i = 0; i < numbers.length; i++) {
document.getElementById("pagination").innerHTML = numbers[i] + "<br>";
}
This replaces the innerHTML
every single time through the loop, so you only see the last iteration.
Try making that =
a +=
.
Or even better, build it up in a string and set the innerHTML
just once with that final string. This will be faster since it only has to parse the string as HTML once instead of 100 times.