문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top