Como utilizar SimplePagination jquery

estou a tentar usara simplepaginação no meu código. (Estou a desenvolver usando MVC4 C#)

Digamos que tenho um monte de códigos.
<table>
    <thead>
        <tr>
            <td><input type="checkbox" name="select-all" id="select-all" /></td>
            <td style="text-align: left">Name</td>
            <td style="text-align: left">Created By</td>
            <td style="text-align: left">Created Date</td>
        </tr>
    </thead>
    <tbody>
        <tr class="post">
            <td><p><input Length="0" name="314" type="checkbox" value="true" /><input name="314" type="hidden" value="false" /></p></td>
            <td>Window</td>
            <td>John</td>
            <td>01/01/2014 12:00:00 AM</td>
        </tr>
        <tr class="post">
            <td><p><input Length="0" name="314" type="checkbox" value="true" /><input name="314" type="hidden" value="false" /></p></td>
            <td>Door</td>
            <td>Chris</td>
            <td>01/01/2014 12:00:00 AM</td>
        </tr>
        <tr class="post">
            <td><p><input Length="0" name="314" type="checkbox" value="true" /><input name="314" type="hidden" value="false" /></p></td>
            <td>Floor</td>
            <td>Michael</td>
            <td>01/01/2014 12:00:00 AM</td>
        </tr>
        <tr class="post">
            <td><p><input Length="0" name="314" type="checkbox" value="true" /><input name="314" type="hidden" value="false" /></p></td>
            <td>Car</td>
            <td>James</td>
            <td>01/01/2014 12:00:00 AM</td>
        </tr>
        <tr class="post">
            <td><p><input Length="0" name="314" type="checkbox" value="true" /><input name="314" type="hidden" value="false" /></p></td>
            <td>Bike</td>
            <td>Steven</td>
            <td>01/01/2014 12:00:00 AM</td>
        </tr>
    </tbody>
</table>

* nota: no código acima, adiciono a classe "post" a cada " tr " (linha no corpo da tabela). E estas linhas são geradas dinamicamente por loop (C#)

e a partir da documentação se eu quiser usar simplepaginação tenho que declarar o jquery assim:

$(function() {
    $(selector).pagination({
        items: 100,
        itemsOnPage: 10,
        cssStyle: 'light-theme'
    });
});

na verdade, não sei bem como usar (*como usar call) this simplePagination. É a primeira vez que lido com paginação.

já tentei colocar este código depois da tabela

<div class="pagination-page"></div>

e mudar o' Selector 'dentro do método de chamada jquery com'.pagination-page', mas não funcionou.

$(function() {
    $('.pagination-page').pagination({
        items: 100,
        itemsOnPage: 10,
        cssStyle: 'light-theme'
    });
});
  1. devo substituir o 'Selector' por um nome de classe? Em caso afirmativo, como faço isso?
  2. O segundo é como eu declaro este simplepaginação para que ele mostre apenas 2 linhas (apenas 2 classe 'Post') para cada page?

* significa que na primeira página só vai mostrar

+--------------------------------------------------+
| [] |  Name  | CreatedBy | CreatedDate            | 
|--------------------------------------------------| 
| [] | Window | John      | 01/01/2014 12:00:00 AM | 
| [] | Door   | Chris     | 01/01/2014 12:00:00 AM | 
+--------------------------------------------------+

a segunda página irá mostrar

+--------------------------------------------------+
| [] |  Name  | CreatedBy | CreatedDate            | 
|--------------------------------------------------| 
| [] | Floor  | Michael   | 01/01/2014 12:00:00 AM | 
| [] | Car    | James     | 01/01/2014 12:00:00 AM | 
+--------------------------------------------------+
Assim por diante..

* Nota: não sei como este jquery irá detectar quantos itens temos e gerar número de páginas e colocar esses itens em conformidade.

Author: Toastrackenigma, 2014-01-03

6 answers

Uma coisa a notar sobre este plugin, sobre o qual algumas pessoas podem ficar confusas, é que tecnicamente não implementa a paginação em si. Ele gera um navegador de página e fornece os meios, através de eventos jQuery, para simplesmente conectá-lo à nossa própria funcionalidade de paginação.

Assumindo que seguiu os passos 1 (e 2 Se quiser o estilo CSS) requerido da ligação {[[5]}simplepaginação que incluiu na sua pergunta, então o seguinte jQuery fará o que você necessidade:

jQuery(function($) {
    // Consider adding an ID to your table
    // incase a second table ever enters the picture.
    var items = $("table tbody tr");

    var numItems = items.length;
    var perPage = 2;

    // Only show the first 2 (or first `per_page`) items initially.
    items.slice(perPage).hide();

    // Now setup the pagination using the `.pagination-page` div.
    $(".pagination-page").pagination({
        items: numItems,
        itemsOnPage: perPage,
        cssStyle: "light-theme",

        // This is the actual page changing functionality.
        onPageClick: function(pageNumber) {
            // We need to show and hide `tr`s appropriately.
            var showFrom = perPage * (pageNumber - 1);
            var showTo = showFrom + perPage;

            // We'll first hide everything...
            items.hide()
                 // ... and then only show the appropriate rows.
                 .slice(showFrom, showTo).show();
        }
    });



    // EDIT: Let's cover URL fragments (i.e. #page-3 in the URL).
    // More thoroughly explained (including the regular expression) in: 
    // https://github.com/bilalakil/bin/tree/master/simplepagination/page-fragment/index.html

    // We'll create a function to check the URL fragment
    // and trigger a change of page accordingly.
    function checkFragment() {
        // If there's no hash, treat it like page 1.
        var hash = window.location.hash || "#page-1";

        // We'll use a regular expression to check the hash string.
        hash = hash.match(/^#page-(\d+)$/);

        if(hash) {
            // The `selectPage` function is described in the documentation.
            // We've captured the page number in a regex group: `(\d+)`.
            $(".pagination-page").pagination("selectPage", parseInt(hash[1]));
        }
    };

    // We'll call this function whenever back/forward is pressed...
    $(window).bind("popstate", checkFragment);

    // ... and we'll also call it when the page has loaded
    // (which is right now).
    checkFragment();



});

Você pode encontrar um exemplo em execução {[[9]} aqui, e um guia mais completo sobre simplepaginação aqui Se você quiser entender mais completamente como tudo isso realmente funciona.

EDIT: adicionou uma secção de código para lidar com fragmentos de URL (na recarga e no back/forward), dado que Mike O'Connor realçou a necessidade. Você pode ver um exemplo vivo de manipulação de fragmentos de URL Aqui .

EDIT 2: Se necessitar de compatibilidade cruzada com o navegador para a actualização do fragmento para trás/para a frente (isto é, IE11...), inclui a história .script js antes de implementar o código acima. Graças ao Mike O'Connor por isso.

Edite 3: Se estiver a adicionar ou a remover dinamicamente o conteúdo, terá de actualizar manualmente o paginador para reflectir estas alterações. Também criei um exemplo para isso. Você pode vê-lo correndo aqui.

 45
Author: Bilal Akil, 2018-01-31 22:02:53
Testei o jQuery do Bilal Akil (função$) e foi um bom começo para mim, obrigado Bilal. Funciona, mas com algumas deficiências. Para um, se você for para seu primeiro link e clicar em uma página 2, então esse número aparece na caixa de localização como " http://bilalakil.github.io/bin/simplepagination/#page-2 " - - - na #page-2. Mas se você copiar esse URL inteiro e colá-lo na caixa de localização de outra página ou janela para simular alguém ligando para a Página 2, então ele plano se não funcionar, vais encontrar-te na página 1. Ou depois de clicar no botão Página 2 e ir para a Página 2, você pode simplesmente recarregar a página; você vai encontrar-se na página 1. Eu teria comentado, mas preciso de deixar aqui um código. Aqui está o meu jQuery modificado(função ($) com a correção desse problema em particular:
  var items = $("#content .page");
  var numItems = items.length;
  var hashPageNum = getPageNum();  //code for getPageNum() is below
  items.hide().slice(hashPageNum-1, hashPageNum).show();

  // now setup pagination
  $("#pagination").pagination({

    items: numItems,
    itemsOnPage: 1,
    cssStyle: "light-theme",
    onPageClick: function(pageNumber) {
    items.hide().slice(pageNumber-1, pageNumber).show();
    }

  });
  $('#pagination').pagination('drawPage', hashPageNum);

Devia ter prefaciado isto dizendo que o esquema de selecção que estou a usar para os elementos da página é o seguinte:

<div id="pagination"></div>
<table id="content"><tbody><tr class="page"><td>...
E estou a usar apenas perplexidade=1, uma por página, mas a diferença essencial é esta linha:
items.hide().slice(hashPageNum-1, hashPageNum).show();

É a principal solução para esse problema sobre ligações com a #page-n no final não funciona. A última linha também é necessária para esse fim, uma vez que define a barra de paginação com a Página n mostrada selecionada.

O segundo problema é a disfunção total dos botões para trás e para a frente com o código de Bilal. Se você colocar a barra de paginação no fundo de uma página longa os leitores certamente vão querer usar o navegação de página incorporada. editar: O Bilal actualizou desde então o seu código para remover estes problemas. Então aqui está uma função que tem um detalhe essencial para esse fim. É chamado no código acima, mas em um outro lugar também:
function getPageNum(){
  var hashtag = parent.location.hash;
  var hashPageNum = 1; //default
  if (hashtag == '#page-1') {
    hashPageNum=1;
  } else if (hashtag == '#page-2'){
    hashPageNum=2;
  } else if (hashtag == '#page-3') {
    hashPageNum=3;
  } else if (hashtag == '') {
    hashPageNum=1;
    parent.location.hash = '#page-1';
  };
  return hashPageNum;
};
Ok, eu entendo que Não tenho sido sofisticado, mas o detalhe essencial é que se pai.localizacao.hash é nulo, então a função retorna 1, para a página 1 - - - não nulo. Há agora um outro passo, que é ... arma a janela.onpopstate, que é uma coisa HTML5 (espero que isso não cause um problema com navegadores não-html5... comentário se souber tudo sobre isso por favor):
window.onpopstate = function(e){
  var pagenum = getPageNum();
  $("#content .page").hide().slice(pagenum-1, pagenum).show();
  $('#pagination').pagination('drawPage', pagenum);
};
E com isso parece que estou feito. Eu posso copiar os URL ' s com os sufixos #page-N E lançá-los em outro lugar e eles funcionam. Os botões para a frente e para trás funcionam. Note que o bit" drawPage " no código imediatamente acima é simplesmente para ajustar a indicação na barra de paginação.

OK, esta é uma edição em 2/16/2015... para mostrar uma correção para o problema IE11 que é discutido nos comentários. Eu não editei o código acima porque talvez você não queira fazer a correção desta maneira, embora pareça funcionar.

Primeiro vá para Este projecto github e depois digite " t " para ficheiros (hah!) e clique na história.minuto.js e, em seguida, no botão Raw e fazer um SaveAs em seu navegador. Então você estará usando essa biblioteca JavaScript que efetivamente cria eventos popstate (e outros eventos) para navegadores que não os cries.

Agora, no código acima, apague a janela.onpopstate = function(E) {} but save its code block and insert it at the end of the jQuery (function ($), right after $('#pagination').paginação ('drawPage', hashPageNum);, como se segue:
  $(window).on('popstate', function(e) {
  var pagenum = getPageNum();
   $("#content .page").hide().slice(pagenum-1, pagenum).show();
   $('#pagination').pagination('drawPage', pagenum);
  }); 

Editar eu tenho que adicionar que se você colocar um link para uma de suas páginas assim paginadas em seu site - - - por exemplo, sua página inicial provavelmente tem âncoras no menu que vão para algumas de suas páginas paginadas - - - então se você colocar alvo= "_blank" em o link e para o href put www.yourdomain.com/yourpaginatedpage vai correr tudo bem. Vai ser bom porque você não vai estar tentando usar a seta de trás no seu navegador para voltar para a sua página inicial, como a página paginada vai abrir como uma nova página ou nova janela.

Mas..... se você deixar de fora o alvo = "_blank" e assim abrir a página paginada na mesma janela você vai descobrir que o botão de trás não funciona. A história está lá para ver quando você pressiona na seta de trás (na verdade está errado, uma vez que existem duas listagens da sua página imaginada) mas nenhuma quantidade de Click na seta fará com que funcione. A cura é simplesmente colocar www.yourdomain.com/yourpaginatedpage#page-1 como o teu href... com a # page-1. Então a flecha de trás vai funcionar.
 2
Author: Mike O'Connor, 2018-02-02 02:31:44

Testei o jQuery de Bilal Akil (função ($)) e encontrei um erro que gostaria de corrigir - e agradeço a Bilal pelo seu envolvimento neste tópico.

Como não posso postar um comentário ou sugerir uma edição do seu post, vou postar a minha resposta diretamente aqui. Para mais informações, consulte o post do Bilal Akil.

{[[2]} o selector para paginação estava errado (não o mesmo de fato) no código como eu tentei em um site então eu decidi editar seu post e pela maneira que eu adicionei 2 variáveis para garantir flexibilidade para mudanças futuras ou personalização própria.
// mind the slight change below, personal idea of best practices
jQuery(function($) {
    // consider adding an id to your table,
    // just incase a second table ever enters the picture..?
    var items = $("table tbody tr");

    var numItems = items.length;
    var perPage = 2;

    var pagination_placeholder_selector = ".pagination-page"; // put in a variable to ensure proper changes in the future
    var myPageName = "#page-"; // a number will follow for each page

    // only show the first 2 (or "first per_page") items initially
    items.slice(perPage).hide();

    // now setup your pagination
    // you need that .pagination-page div before/after your table
    $(pagination_placeholder_selector).pagination({
        items: numItems,
        itemsOnPage: perPage,
        cssStyle: "light-theme",
        hrefTextPrefix: myPageName,
        onPageClick: function(pageNumber) { // this is where the magic happens
            // someone changed page, lets hide/show trs appropriately
            var showFrom = perPage * (pageNumber - 1);
            var showTo = showFrom + perPage;

            items.hide() // first hide everything, then show for the new page
                 .slice(showFrom, showTo).show();
        }
    });



    // EDIT: extra stuff to cover url fragments (i.e. #page-3)
    // https://github.com/bilalakil/bin/tree/master/simplepagination/page-fragment
    // is more thoroughly commented (to explain the regular expression)

    // we'll create a function to check the url fragment and change page
    // we're storing this function in a variable so we can reuse it
    var checkFragment = function() {
        // if there's no hash, make sure we go to page 1
        var hash = window.location.hash || (myPageName+"1");

        // we'll use regex to check the hash string
        var re = new RegExp("^"+myPageName+"(\\d+)$");
        hash = hash.match(re);

        if(hash)
            // the selectPage function is described in the documentation
            // we've captured the page number in a regex group: (\d+)
            $(pagination_placeholder_selector).pagination("selectPage", parseInt(hash[1]));
    };

    // we'll call this function whenever the back/forward is pressed
    $(window).bind("popstate", checkFragment);

    // and we'll also call it to check right now!
    checkFragment();



});
 0
Author: Devour, 2015-10-29 11:38:47
Converti o trabalho do Bilal Akil numa função e chamei-o a ajax porque estou a carregar dados pela chamada do ajax. Funciona lindamente. Obrigado a todos os participantes.
function paginate() {
// consider adding an id to your table,
// just incase a second table ever enters the picture..?
var items = jQuery("#searched_prfiles .row .col-md-4");

var numItems = items.length;
var perPage = 2;

var pagination_placeholder_selector = "#pagination_links"; // put in a variable to ensure proper changes in the future
var myPageName = "#page-"; // a number will follow for each page

// only show the first 2 (or "first per_page") items initially
items.slice(perPage).hide();

// now setup your pagination
// you need that .pagination-page div before/after your table
jQuery(pagination_placeholder_selector).pagination({
    items: numItems,
    itemsOnPage: perPage,
    cssStyle: "light-theme",
    hrefTextPrefix: myPageName,
    onPageClick: function(pageNumber) { // this is where the magic happens
        // someone changed page, lets hide/show trs appropriately
        var showFrom = perPage * (pageNumber - 1);
        var showTo = showFrom + perPage;

        items.hide() // first hide everything, then show for the new page
             .slice(showFrom, showTo).show();
    }
});



// EDIT: extra stuff to cover url fragments (i.e. #page-3)
// https://github.com/bilalakil/bin/tree/master/simplepagination/page-fragment
// is more thoroughly commented (to explain the regular expression)

// we'll create a function to check the url fragment and change page
// we're storing this function in a variable so we can reuse it
var checkFragment = function() {
    // if there's no hash, make sure we go to page 1
    var hash = window.location.hash || (myPageName+"1");

    // we'll use regex to check the hash string
    var re = new RegExp("^"+myPageName+"(\\d+)$");
    hash = hash.match(re);

    if(hash)
        // the selectPage function is described in the documentation
        // we've captured the page number in a regex group: (\d+)
        jQuery(pagination_placeholder_selector).pagination("selectPage", parseInt(hash[1]));
};

// we'll call this function whenever the back/forward is pressed
jQuery(window).bind("popstate", checkFragment);

// and we'll also call it to check right now!
checkFragment();

}

 0
Author: Muhammad Khalid, 2015-12-15 08:51:13

Primeira adição:

<script type="text/javascript" src="mio_path_js/jquery.js"></script>
<script type="text/javascript" src="mio_path_js/jquery.simplePagination.js"></script>

<link type="text/css" rel="stylesheet" href="mio_path_css/simplePagination.css"/>

E depois, para 10 elementos, chamar a função Ajax como:

$(function() {
  $(#id_paginator").pagination({
    items: 100,
    itemsOnPage: 10,
    cssStyle: 'light-theme'
  });
});

Ou se quiser carregar todo o elemento:

$.Forum({ ...... ...... sucesso: função (Resposta, estado, xhr) { jQuery (função ($) { var pageParts = $(".paginar"); var numPages = countSelect; var perPage = 10; pageParts.fatia (perplexidade).esconder ();

        $("#page-nav").pagination({
        items: numPages,
        itemsOnPage: perPage,
        cssStyle: "light-theme",
        currentPage: numeroSelezionato,
            onPageClick: function(pageNum) {
                $("#myModalWaiting").show();
                var start = perPage * (pageNum - 1);
                var end = start + perPage;
                cambiaPagina(start,end,pageNum);
                numeroSelezionato = pageNum;
            }
        });
    });
}

)};

O código Html riz:

<table>
    <tr>
        <th>
            <td>
                ............
                ...............
                .................
            </td>
        </th>
     </tr></table>
<div id="id_paginator"></div>

enter image description here

Para outro exemplo de simplepaginação Jquery ver Aqui.

Ou para mais elementos a carregar: https://lentux-informatica.com/paginazione-liste-con-jquery-parte-2-2-simplepagination-js/

 0
Author: Rosario Mezzatesta, 2018-07-23 07:19:52

A seguir ao trabalho de código para mim:

function paginationTable() {

    var items = $("table tbody tr");
    var tablaeBody = $("table tbody");
        var numItems = items.length;
        var perPage = 20;

        // Only show the first 20 (or first `per_page`) items initially.
        tablaeBody.html(items.slice(0,20));
        // Now setup the pagination using the `.pagination-page` div.
        $(".pagination-page").pagination({
            items: numItems,
            itemsOnPage: perPage,
            cssStyle: "light-theme",

            // This is the actual page changing functionality.
            onPageClick: function(pageNumber) {
                // We need to show and hide `tr`s appropriately.
                var showFrom = perPage * (pageNumber - 1);
                var showTo = showFrom + perPage;

                tablaeBody.html(items.slice(showFrom,showTo));

            }
        });
}

Ligue para esta função depois de preparar a sua tabela HTML.

 0
Author: Sandip Solanki, 2018-08-21 13:58:39