Paging iterations of a for cycle in Javascript

1

First of all I want to clarify that I do not take for granted that this can be done. My query is if it is possible to page the results of a cycle for in Javascript , let's take the following sample code:

var i = null;
for (i = 0; i <= 100; i++) {
    document.write(i + "<br/>");
    if (i % 10 == 0) {
        document.write("Paginación<br/>");
    }
}

If the code is executed it can be seen that every 10 iterations shows a message (an example), so I wanted to know if it was possible that in this same idea the results could be paged, that is to say, that at the beginning it shows me only the first 10 numbers, and with a button, I can show the next 10 items and so on.

    
asked by Jalkhov 06.04.2018 в 02:31
source

1 answer

3

You can, something similar.

With a loop you would create the elements of the pages. Each page would be saved in a block div , the first of them visible, the rest hidden display: none

With another loop, you would create the page buttons and call them a function to show another page.

var i;
var hasta = 100;
var tamanioPagina = 10;

document.write("<div data-pagina='1'>");
for(i=1; i<=hasta; i++){
    if (i > 1 && i % tamanioPagina == 1){
        document.write('</div><div data-pagina="${(i-1)/tamanioPagina + 1}" style="display: none">');
    }
    document.write(i+"<br/>");
}
document.write("</div>");

var cantidadPaginas = Math.ceil(hasta / tamanioPagina);
for(i=1; i<=cantidadPaginas; i++){
    document.write('<a href="javascript:pagina(${i})">${i}</a>');
}

function pagina(n) {
    var paginas = document.querySelectorAll("div[data-pagina]");
    for(var i=1; i<=paginas.length; ++i){
        paginas[i-1].style = n == i ? "" : "display: none";
    }
}
a {
    padding-right: 10px;
}
    
answered by 06.04.2018 / 03:23
source