How to use pagination on HTML tables?

前端 未结 8 588
长发绾君心
长发绾君心 2020-12-07 21:41

I am trying to use this Pagination library in my HTML table page (specifically light theme) but somehow I am not able to understand how to plugin this library in such a way

相关标签:
8条回答
  • 2020-12-07 21:44

    It is a very simple and effective utility build in jquery to implement pagination on html table http://tablesorter.com/docs/example-pager.html

    Download the plugin from http://tablesorter.com/addons/pager/jquery.tablesorter.pager.js

    After adding this plugin add following code in head script

    $(document).ready(function() { 
        $("table") 
        .tablesorter({widthFixed: true, widgets: ['zebra']}) 
        .tablesorterPager({container: $("#pager")}); 
    }); 
    
    0 讨论(0)
  • 2020-12-07 21:44

    There's a easy way to paginate a table using breedjs (jQuery plugin), see the example:

    HTML

    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Gender</th>
          <th>Age</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr b-scope="people" b-loop="person in people" b-paginate="5">
          <td>{{person.name}}</td>
          <td>{{person.gender}}</td>
          <td>{{person.age}}</td>
          <td>{{person.email}}</td>
        </tr>
      </tbody>
    </table>
    <ul></ul>
    

    JS

    var data={ people: [ {...}, {...}, ...] };
    
    $(function() {
      breed.run({
        scope: 'people',
        input: data,
        runEnd: function(){ //This runEnd is just to mount the page buttons
            for(i=1 ; i<=breed.getPageCount('people') ; i++){
            $('ul').append(
                $('<li>',{
                html: i,
                onclick: "breed.paginate({scope: 'people', page: " + i + "});"
              })
            );
          }
        }
      });
    });
    

    Every time you want to change pages, just call:

    breed.paginate({scope: 'people', page: pageNumber);
    

    More info.

    Working example.

    0 讨论(0)
  • 2020-12-07 21:46

    Many times we might want to perform Table pagination using jquery.Here i ll give you the answer and reference link

    Jquery

      $(document).ready(function(){
            $('#data').after('<div id="nav"></div>');
            var rowsShown = 4;
            var rowsTotal = $('#data tbody tr').length;
            var numPages = rowsTotal/rowsShown;
            for(i = 0;i < numPages;i++) {
                var pageNum = i + 1;
                $('#nav').append('<a href="#" rel="'+i+'">'+pageNum+'</a> ');
            }
            $('#data tbody tr').hide();
            $('#data tbody tr').slice(0, rowsShown).show();
            $('#nav a:first').addClass('active');
            $('#nav a').bind('click', function(){
    
                $('#nav a').removeClass('active');
                $(this).addClass('active');
                var currPage = $(this).attr('rel');
                var startItem = currPage * rowsShown;
                var endItem = startItem + rowsShown;
                $('#data tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).
                        css('display','table-row').animate({opacity:1}, 300);
            });
        });
    

    JSfiddle: https://jsfiddle.net/u9d1ewsh/

    0 讨论(0)
  • 2020-12-07 21:49

    For me, best and simplest way, Bootply http://www.bootply.com/lxa0FF9yhw#

    First include Bootstrap to your project

    Then include javascript file in which you write this code:

        $.fn.pageMe = function(opts){
        var $this = this,
            defaults = {
                perPage: 7,
                showPrevNext: false,
                hidePageNumbers: false
            },
            settings = $.extend(defaults, opts);
    
        var listElement = $this;
        var perPage = settings.perPage; 
        var children = listElement.children();
        var pager = $('.pager');
    
        if (typeof settings.childSelector!="undefined") {
            children = listElement.find(settings.childSelector);
        }
    
        if (typeof settings.pagerSelector!="undefined") {
            pager = $(settings.pagerSelector);
        }
    
        var numItems = children.size();
        var numPages = Math.ceil(numItems/perPage);
    
        pager.data("curr",0);
    
        if (settings.showPrevNext){
            $('<li><a href="#" class="prev_link">«</a></li>').appendTo(pager);
        }
    
        var curr = 0;
        while(numPages > curr && (settings.hidePageNumbers==false)){
            $('<li><a href="#" class="page_link">'+(curr+1)+'</a></li>').appendTo(pager);
            curr++;
        }
    
        if (settings.showPrevNext){
            $('<li><a href="#" class="next_link">»</a></li>').appendTo(pager);
        }
    
        pager.find('.page_link:first').addClass('active');
        pager.find('.prev_link').hide();
        if (numPages<=1) {
            pager.find('.next_link').hide();
        }
        pager.children().eq(1).addClass("active");
    
        children.hide();
        children.slice(0, perPage).show();
    
        pager.find('li .page_link').click(function(){
            var clickedPage = $(this).html().valueOf()-1;
            goTo(clickedPage,perPage);
            return false;
        });
        pager.find('li .prev_link').click(function(){
            previous();
            return false;
        });
        pager.find('li .next_link').click(function(){
            next();
            return false;
        });
    
        function previous(){
            var goToPage = parseInt(pager.data("curr")) - 1;
            goTo(goToPage);
        }
    
        function next(){
            goToPage = parseInt(pager.data("curr")) + 1;
            goTo(goToPage);
        }
    
        function goTo(page){
            var startAt = page * perPage,
                endOn = startAt + perPage;
    
            children.css('display','none').slice(startAt, endOn).show();
    
            if (page>=1) {
                pager.find('.prev_link').show();
            }
            else {
                pager.find('.prev_link').hide();
            }
    
            if (page<(numPages-1)) {
                pager.find('.next_link').show();
            }
            else {
                pager.find('.next_link').hide();
            }
    
            pager.data("curr",page);
            pager.children().removeClass("active");
            pager.children().eq(page+1).addClass("active");
    
        }
    };
    

    You need to give an id to the tbody of your table and to add a 'div' after the table for the pagination

         <table class="table" id="myTable">
                <thead>
                    <tr>
                        <th>...</th>
                    </tr>
                </thead>
                <tbody id="myTableBody">
                </tbody>
           </table>
           <div class="col-md-12 text-center">
               <ul class="pagination pagination-lg pager" id="myPager"></ul>
           </div>
    

    When your table's data is loaded, just call this

    $('#myTableBody').pageMe({pagerSelector:'#myPager',showPrevNext:true,hidePageNumbers:false,perPage:4});
    

    where the 'perPage' value is to set how many elements per page you want to have.

    0 讨论(0)
  • 2020-12-07 21:53

    With Reference to Anusree answer above and with respect,I am tweeking the code little bit to make sure it works in most of the cases.

    1. Created a reusable function paginate('#myTableId') which can be called any number times for any table.
    2. Adding code inside ajaxComplete function to make sure paging is called once table using jquery is completely loaded. We use paging mostly for ajax based tables.
    3. Remove Pagination div and rebind on every pagination call
    4. Configuring Number of rows per page

    Code:

    $(document).ready(function () {
        $(document).ajaxComplete(function () {
            paginate('#myTableId',10);
            function paginate(tableName,RecordsPerPage) {
                $('#nav').remove();
                $(tableName).after('<div id="nav"></div>');
                var rowsShown = RecordsPerPage;
                var rowsTotal = $(tableName + ' tbody tr').length;
                var numPages = rowsTotal / rowsShown;
                for (i = 0; i < numPages; i++) {
                    var pageNum = i + 1;
                    $('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
                }
                $(tableName + ' tbody tr').hide();
                $(tableName + ' tbody tr').slice(0, rowsShown).show();
                $('#nav a:first').addClass('active');
                $('#nav a').bind('click', function () {
    
                    $('#nav a').removeClass('active');
                    $(this).addClass('active');
                    var currPage = $(this).attr('rel');
                    var startItem = currPage * rowsShown;
                    var endItem = startItem + rowsShown;
                    $(tableName + ' tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
                        css('display', 'table-row').animate({ opacity: 1 }, 300);
                });
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-07 22:01

    Pure js. Can apply it to multiple tables at once. Aborts if only one page is required. I used anushree as my starting point.

    Sorry to the asker, obviously this is not a simplePagignation.js solution. However, it's the top google result when you type "javascript table paging", and it's a reasonable solution to many who may be considering a library but unsure whether to go that route or not.

    Use like this:

    addPagerToTables('#someTable', 8);
    

    Requires no css, though it may be wise to initially hide table tBody rows in css anyway to prevent the effect of rows showing then quicky being hidden (not happening with me right now, but it's something I've seen before).

    The code:

    function addPagerToTables(tables, rowsPerPage = 10) {
    
        tables = 
            typeof tables == "string"
          ? document.querySelectorAll(tables)
          : tables;
    
        for (let table of tables) 
            addPagerToTable(table, rowsPerPage);
    
    }
    
    function addPagerToTable(table, rowsPerPage = 10) {
    
        let tBodyRows = table.querySelectorAll('tBody tr');
        let numPages = Math.ceil(tBodyRows.length/rowsPerPage);
    
        let colCount = 
        [].slice.call(
            table.querySelector('tr').cells
        )
        .reduce((a,b) => a + parseInt(b.colSpan), 0);
    
        table
        .createTFoot()
        .insertRow()
        .innerHTML = `<td colspan=${colCount}><div class="nav"></div></td>`;
    
        if(numPages == 1)
            return;
    
        for(i = 0;i < numPages;i++) {
    
            let pageNum = i + 1;
    
            table.querySelector('.nav')
            .insertAdjacentHTML(
                'beforeend',
                `<a href="#" rel="${i}">${pageNum}</a> `        
            );
    
        }
    
        changeToPage(table, 1, rowsPerPage);
    
        for (let navA of table.querySelectorAll('.nav a'))
            navA.addEventListener(
                'click', 
                e => changeToPage(
                    table, 
                    parseInt(e.target.innerHTML), 
                    rowsPerPage
                )
            );
    
    }
    
    function changeToPage(table, page, rowsPerPage) {
    
        let startItem = (page - 1) * rowsPerPage;
        let endItem = startItem + rowsPerPage;
        let navAs = table.querySelectorAll('.nav a');
        let tBodyRows = table.querySelectorAll('tBody tr');
    
        for (let nix = 0; nix < navAs.length; nix++) {
    
            if (nix == page - 1)
                navAs[nix].classList.add('active');
            else 
                navAs[nix].classList.remove('active');
    
            for (let trix = 0; trix < tBodyRows.length; trix++) 
                tBodyRows[trix].style.display = 
                    (trix >= startItem && trix < endItem)
                    ? 'table-row'
                    : 'none';  
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题