简体   繁体   English

如何使用jQuery对多个HTML正文进行分页

[英]How to paginate multiple HTML tbodies with jQuery

I have this table drawn from d3 where it has grouped entries that are in separate tbodies so the entries stay grouped when sorted. 我从d3中提取了这张表,在此表中,有分组的条目位于单独的tbobody中,因此在排序时条目保持分组状态。 I am using the tablesorter plugin to help sort the tbodies which as been nothing but awesome, however at this point, you cannot use their pagination widget with the sortable tbodies one. 我正在使用tablesorter插件来帮助对tbodies进行排序,这真是棒极了,但是在这一点上,您不能将它们的分页小部件与可排序的tbodies一起使用。

I have d3 handling all the table drawing, so it would be great if there was a plugin out there that can handle this. 我有d3处理所有表格绘图,因此如果那里有一个可以处理此问题的插件,那就太好了。 I had to use d3 this time since I needed a sortable nested table that wouldn't case the groups to break apart when sorting, otherwise the datatables plugin would have been good. 这次我不得不使用d3,因为我需要一个可排序的嵌套表,该表不会在排序时使组分开,否则datatables插件会很好。 It's sort of like a billing statement where you can view several accounts that have a summary and then the details. 有点像帐单,您可以在其中查看多个具有摘要的帐户,然后查看详细信息。 D3 allowed the nested groupings to happen and the tablesorter plugin was great to allow sorting of both the details and the totals of the data. D3允许嵌套分组的发生,并且tablesorter插件很棒,可以同时对详细信息和数据总计进行排序。 Is there a way D3 or any other tool can do pagination for all the tbodies? D3或任何其他工具是否可以对所有主体进行分页?

To solve this problem, I tried to use traditional paginators, but those only work on regular tables. 为了解决此问题,我尝试使用传统的分页器,但这些分页器仅适用于常规表。 This is a D3 table that has nested tables and it's important it can sort on the details and summaries. 这是一个具有嵌套表的D3表,很重要的一点是它可以对详细信息和摘要进行排序。 Here's a fiddle of what I am dealing with: https://jsfiddle.net/mcsmitheslc/mns6183o/ 这是我正在处理的东西的小提琴: https : //jsfiddle.net/mcsmitheslc/mns6183o/

This is a paginator I had somewhat working, but it seems like overkill do do it all by hand like this: 这是我曾经做过的分页器,但看起来像是过分杀手,是这样手工完成的:

    // Paginate the table, there's a plugin but it's not able to handle the nesting yet
    $('.paginated').each(function () {
        var $table = $(this);
        var itemsPerPage = 25;
        var currentPage = 0;
        var pages = Math.ceil($table.find("tr.detail-row:not(:has(th))").length / itemsPerPage);
        var allRows = merged.length;
        var shownRows = $('#table .detail-row:visible').length;

        $table.bind('repaginate', function () {
            if (pages > 1) {
                var pager;
                if ($table.next().hasClass("pager")) {
                    pager = $table.next().empty();
                } else
                    pager = $('<div class="pager" id="" style="padding-top: 20px; direction:ltr; " align="center"></div>');

                $('<button class="button hollow" id="first-button"></button>').text(' « First ').bind('click', function () {
                    currentPage = 0;
                    $table.trigger('repaginate');

                }).appendTo(pager);

                $('<button class="button hollow" id="previous-button"> « Prev </button>').bind('click', function () {
                    if (currentPage > 0)
                        currentPage--;
                    $table.trigger('repaginate');
                }).appendTo(pager);

                var startPager = currentPage > 2 ? currentPage - 2 : 0;
                var endPager = startPager > 0 ? currentPage + 3 : 5;
                if (endPager > pages) {
                    endPager = pages;
                    startPager = pages - 5;
                    if (startPager < 0)
                        startPager = 0;
                }

                for (var page = startPager; page < endPager; page++) {
                    $('<button id="pager-button" class="button tiny"><span id="pg' + page + '" class="' + (page == currentPage ? 'pg-selected' : 'pg-normal') + '"></span></button>').text(page + 1).bind('click', {
                        newPage: page
                    }, function (event) {
                        currentPage = event.data['newPage'];
                        $table.trigger('repaginate');
                    }).appendTo(pager);
                }

                $('<button class="button hollow" id="next-button"> Next » </button>').bind('click', function () {
                    if (currentPage < pages - 1)
                        currentPage++;
                    $table.trigger('repaginate');
                    console.log('Viewing ' +currentPage);
                }).appendTo(pager);
                $('<button class="button hollow" id="last-button"> Last » </button>').bind('click', function () {
                    currentPage = pages - 1;
                    $table.trigger('repaginate');
                    var rowCount = $('#table tbody tr').length;
                    var numOfVisibleRows = $('tbody tr:visible').length;
                    var diff = currentPage * 25;
                    var remainingRows = allRows - diff;
                    console.log('Viewing ' +currentPage);
                    console.log(diff + 'sliced' +remainingRows + ' on the last page');
                }).appendTo(pager);

                if (!$table.next().hasClass("pager"))
                    pager.insertAfter($table);
            }
            $table.find(
                'tbody tr:not(:has(th))').hide().slice(currentPage * itemsPerPage, (currentPage + 1) * itemsPerPage).show();

        });

        $table.trigger('repaginate');

    });

Glad you came back with what you've tried until now based off the comment I posted. 很高兴您根据我发表的评论回到了自己到目前为止一直尝试的方法。 I couldn't work on it yesterday as I got too busy with work. 昨天因为工作太忙,我无法继续工作。 Anyway, got it working now. 无论如何,现在就可以使用了。

I made a few changes to it and also added certain additional features (First, Prev, Next, Last) and seems to be working okay now. 我对其进行了一些更改,还添加了某些其他功能(“第一”,“上一”,“下一”,“最后”),现在看来可以正常工作。

HTML added: 新增HTML:

<div id="toggle-buttons">
<button class="button" data-id="first">
          First Page
        </button>
<button class="button disabled" data-id="previous">
          Prev Page
        </button>
<button class="button" data-id="next">
          Next Page
        </button>
<button class="button" data-id="last">
          Last Page
        </button>            
<button class="button" id="all-button">
          Show All
</button>
</div>

Javascript to paginate the table based on the button click: 基于单击按钮对表进行分页的Javascript:

const totalBodies = $('tbody').length;
var counter = 0; // set counter initially to 0

d3.selectAll('#toggle-buttons button').on('click', function () {

if(d3.select(this).classed('disabled'))
    return ;

switch(d3.select(this).attr('data-id')) {
    case 'first':
        counter = 0;
    d3.select(this.parentNode).select('[data-id="previous"]').classed('disabled', true);
    d3.select(this.parentNode).select('[data-id="next"]').classed('disabled', false);
            break;
  case 'last':
        counter = totalBodies-1;
    d3.select(this.parentNode).select('[data-id="next"]').classed('disabled', true);        
    d3.select(this.parentNode).select('[data-id="previous"]').classed('disabled', false);        
    break;
  case 'next':
            counter++;
    if(counter === totalBodies-1) {
        d3.select(this).classed('disabled', true);
    }
        d3.select(this.parentNode).select('[data-id="previous"]').classed('disabled', false);         
    break;
  case 'previous':
            counter--;
    if(!counter) {
        d3.select(this).classed('disabled', true);
    }
        d3.select(this.parentNode).select('[data-id="next"]').classed('disabled', false);         
            break;
}
redraw(counter);
});

Explanation (pretty much understandable I suppose): 说明(我想是可以理解的):

  1. Switch case to determine the button click based on which the counter will change. 切换大小写,以根据计数器的变化确定按钮的单击。 Important Toggling the disabled class on the buttons. 重要提示在按钮上切换disabled类。
  2. redraw(counter) on every button click (unless it has a disabled class) 每次单击按钮都会redraw(counter) (除非它具有禁用的类)

Here's a fork of your fiddle: 这是您的小提琴叉子:

https://jsfiddle.net/shashank2104/noxg31eq/ https://jsfiddle.net/shashank2104/noxg31eq/

I'm selecting the first page by default. 我默认选择第一页。 You can change that according to the requirement and add the disabled class in the initial phase accordingly. 您可以根据要求进行更改,并在初始阶段相应地添加disabled类。 Also, I see a table nested within a table which doesn't seem right - maybe tablesorter adds a table tag as well. 另外,我看到一个table嵌套在一个内table这看起来不正确-也许tablesorter增加了一个table标签为好。 You can take a look at that. 您可以看一下。

Hope this helps. 希望这可以帮助。

I got some of it myself based off what Shashank posted: 我自己是根据Shashank发布的内容获得的:

        let tbodiesPerPage = 10;
    const totalBodies = $('tbody').length;

    d3.select("#buttons").datum({
        portion: 0
    });

    // the chain select here pushes the datum onto the up and down buttons also
    d3.select("#buttons").select("#previous-button").on("click", function (d) {
        console.log('next was ', d.portion);
        if (d.portion - tbodiesPerPage >= 0) {
            d.portion -= tbodiesPerPage;
            redraw(d.portion);
        }
    });

    d3.select("#buttons").select("#next-button").on("click", function (d) {
        // let the bodies hit the floor
        console.log('previous was', d.portion);
        if (d.portion < (totalBodies - tbodiesPerPage)) {
            d.portion += tbodiesPerPage;
            redraw(d.portion);
        }
    });

    function redraw(start) {
        d3
            .select("table")
            .selectAll("tr")
            .style("display", function (d, i) {
                return i >= start && i < start + tbodiesPerPage ? null : "none";
            });
    }

    redraw(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM