【问题标题】:Limit the number of visible pages in pagination限制分页中可见页面的数量
【发布时间】:2018-03-05 01:26:04
【问题描述】:

我正在开发一个 jQuery 分页工具,虽然我有分页工作,但我发现了一个缺陷:

拥有一排 14 个以上的分页链接在桌面上是可以的,但对于移动设备来说就不行了。所以我想一次将可见页面的数量限制为 5 个(不包括下一个/上一个按钮),并在它到达第三个可见页面时更新它并更新分页中的可见页面,基本上看起来像

| Prev | 1 | ... | 3 | 4 | 5 | 6 | Next |

我已经写了this CodePen 到目前为止的所有内容。我知道有插件可以为我执行此操作,但我想避免在此项目中使用插件。

HTML(分页的示例内容)

<div class="container" id="jar">
    <div class="row content">
         <div class="col">
              <img src="http://via.placeholder.com/350x150">
         </div>
         <div class="col">
             <img src="http://via.placeholder.com/350x150">
         </div>
    </div>
</div>

HTML(分页元素)

 <nav>
   <ul class="pagination justify-content-center pagination-sm">
     <li id="previous-page" class="page-item"><a class="page-link" href="javascript:void(0)">Prev</a>
     </li>
   </ul>
 </nav>

JavaScript:

"use strict";
 //NOTE: the class"page-item page-link" are classes used in bootstrap 4 and will not be seen declared or used outside of the <li> as the bootstrap framework uses those classes to apply CSS

 //sets number of items and limits the number of items per page

var numberOfItems = $("#jar .content").length;
var limitPerPage = 2;

//as the items start at 0 to keep the items per page at the limitPerPage set in variable, need to subtract 1 as is shown below

$("#jar .content:gt(" + (limitPerPage - 1) + ")").hide();

//sets total pages rounded to the next whole number

var totalPages = Math.round(numberOfItems / limitPerPage);

//append the 1 page to the pagination

$(".pagination").append(
        "<li class='page-item current-page active'><a class='page-link'  href='javascript:void(0)'>" +
        1 +
        "</a></li>"
        );

//append the pages in sequential order after prev button (as seen in the html in codepen)

for (var i = 2; i <= totalPages; i++) {
    $(".pagination").append(
            "<li class='page-item current-page'><a class='page-link' href='javascript:void(0)'>" +
            i +
            "</a></li>"
            );
}

//appends the next button link as the final child element in the pagination

$(".pagination").append(
        "<li class='page-item' id='next-page'><a class='page-link' href='javascript:void(0)'>Next</a></li>"
        );

//When a page is selected, if it has "active" class return false, if no "active" class, go to page and add "active" class attribute and remove from any other element that has "active" on it.

$(".pagination li.current-page").on("click", function () {
    if ($(this).hasClass("active")) {
        return false;
    } else {
        var currentPage = $(this).index();
        $(".pagination li").removeClass("active");
        $(this).addClass("active");
        $("#jar .content").hide();

       //.hide will hide content that does not fit into that page (ie 0 and 1 on page one, 2 and 3 on page two and so on will show on appropriate page)  If it does not fall within the range for that page .hide, if it falls within the range .show content

        var grandTotal = limitPerPage * currentPage;

        for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
            $("#jar .content:eq(" + i + ")").show();
        }
    }
});

//when next is clicked if it is on the last page, return false otherwise move on to next page in pagination and remove "active" class from previous page and add "active" class to new page

$("#next-page").on("click", function () {
    var currentPage = $(".pagination li.active").index();
    if (currentPage === totalPages) {
        return false;
    } else {
        currentPage++;
        $(".pagination li").removeClass("active");
        $("#jar .content").hide();

        var grandTotal = limitPerPage * currentPage;

        for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
            $("#jar .content:eq(" + i + ")").show();
        }
        $(".pagination li.current-page:eq(" + (currentPage - 1) + ")").addClass(
                "active"
                );
    }
});

//when prev is clicked if it is on the 1 page, return false otherwise move on to previous page and remove "active" class from last page visited and add "active" class to new page

$("#previous-page").on("click", function () {
    var currentPage = $(".pagination li.active").index();
    if (currentPage === 1) {
        return false;
    } else {
        currentPage--;
        $(".pagination li").removeClass("active");
        $("#jar .content").hide();

        var grandTotal = limitPerPage * currentPage;

        for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
            $("#jar .content:eq(" + i + ")").show();
        }
        $(".pagination li.current-page:eq(" + (currentPage - 1) + ")").addClass(
                "active"
                );
    }
});

【问题讨论】:

  • 分享您的研究对每个人都有帮助。告诉我们您尝试了什么以及为什么它不能满足您的需求。这表明您已经花时间尝试帮助自己,它使我们免于重复明显的答案,最重要的是它可以帮助您获得更具体和相关的答案!另见:How to Ask
  • 我查看了不同插件的 js 文件,看看他们是如何做到的,大多数似乎破坏了分页并在达到某个页码阈值时重新绘制它。我不确定如何使用我编写的代码来复制它,因为我看过的插件并没有准确地解释他们对代码的每个部分做了什么。我查看了 YouTube 教程,在那里我找到了一个可以帮助编写此内容的教程,但没有找到一个可以帮助解释如何销毁和重绘分页的教程。
  • 您应该考虑提供minimal reproducible example。我不想通读并尝试理解您发布的代码,因为老实说,它看起来很糟糕。
  • 格式化代码
  • 将 cmets 添加到 jquery 以及添加 html 示例(复制和粘贴以“row”类开头并保存在 id="jar" 的容器中,以便在测试时创建多个页面)。分页导航元素不需要在同一个容器中。如果您想查看实际代码以供参考,请使用this codepen

标签: jquery pagination


【解决方案1】:

我建议使用一个函数——给定当前页码、总页数和你想要的最大按钮数——将返回一个数字数组,其中 0 表示 ... 按钮,其他数字表示可点击的页面按钮。

例如,它可以返回:

[1, 2, 0, 5, 6, 7, 0, 10, 11]

...代表以下按钮:

12...567...1011

这个函数会计算那些 ... 应该放在哪里,但是一旦你有了它,将它与你的页面集成起来就是小菜一碟。

这是一个将按钮数量限制为 7 个的示例(不包括 prev/next,包括 ... 按钮)。如果您愿意,可以将该参数减少到 5:

// Returns an array of maxLength (or less) page numbers
// where a 0 in the returned array denotes a gap in the series.
// Parameters:
//   totalPages:     total number of pages
//   page:           current page
//   maxLength:      maximum size of returned array
function getPageList(totalPages, page, maxLength) {
    if (maxLength < 5) throw "maxLength must be at least 5";

    function range(start, end) {
        return Array.from(Array(end - start + 1), (_, i) => i + start); 
    }

    var sideWidth = maxLength < 9 ? 1 : 2;
    var leftWidth = (maxLength - sideWidth*2 - 3) >> 1;
    var rightWidth = (maxLength - sideWidth*2 - 2) >> 1;
    if (totalPages <= maxLength) {
        // no breaks in list
        return range(1, totalPages);
    }
    if (page <= maxLength - sideWidth - 1 - rightWidth) {
        // no break on left of page
        return range(1, maxLength - sideWidth - 1)
            .concat(0, range(totalPages - sideWidth + 1, totalPages));
    }
    if (page >= totalPages - sideWidth - 1 - rightWidth) {
        // no break on right of page
        return range(1, sideWidth)
            .concat(0, range(totalPages - sideWidth - 1 - rightWidth - leftWidth, totalPages));
    }
    // Breaks on both sides
    return range(1, sideWidth)
        .concat(0, range(page - leftWidth, page + rightWidth),
                0, range(totalPages - sideWidth + 1, totalPages));
}

// Below is an example use of the above function.
$(function () {
    // Number of items and limits the number of items per page
    var numberOfItems = $("#jar .content").length;
    var limitPerPage = 2;
    // Total pages rounded upwards
    var totalPages = Math.ceil(numberOfItems / limitPerPage);
    // Number of buttons at the top, not counting prev/next,
    // but including the dotted buttons.
    // Must be at least 5:
    var paginationSize = 7; 
    var currentPage;

    function showPage(whichPage) {
        if (whichPage < 1 || whichPage > totalPages) return false;
        currentPage = whichPage;
        $("#jar .content").hide()
            .slice((currentPage-1) * limitPerPage, 
                    currentPage * limitPerPage).show();
        // Replace the navigation items (not prev/next):            
        $(".pagination li").slice(1, -1).remove();
        getPageList(totalPages, currentPage, paginationSize).forEach( item => {
            $("<li>").addClass("page-item")
                     .addClass(item ? "current-page" : "disabled")
                     .toggleClass("active", item === currentPage).append(
                $("<a>").addClass("page-link").attr({
                    href: "javascript:void(0)"}).text(item || "...")
            ).insertBefore("#next-page");
        });
        // Disable prev/next when at first/last page:
        $("#previous-page").toggleClass("disabled", currentPage === 1);
        $("#next-page").toggleClass("disabled", currentPage === totalPages);
        return true;
    }

    // Include the prev/next buttons:
    $(".pagination").append(
        $("<li>").addClass("page-item").attr({ id: "previous-page" }).append(
            $("<a>").addClass("page-link").attr({
                href: "javascript:void(0)"}).text("Prev")
        ),
        $("<li>").addClass("page-item").attr({ id: "next-page" }).append(
            $("<a>").addClass("page-link").attr({
                href: "javascript:void(0)"}).text("Next")
        )
    );
    // Show the page links
    $("#jar").show();
    showPage(1);

    // Use event delegation, as these items are recreated later    
    $(document).on("click", ".pagination li.current-page:not(.active)", function () {
        return showPage(+$(this).text());
    });
    $("#next-page").on("click", function () {
        return showPage(currentPage+1);
    });

    $("#previous-page").on("click", function () {
        return showPage(currentPage-1);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

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

<div id="jar" style="display:none">
    <div class="content">1) Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
    <div class="content">2) Maecenas vitae elit arcu.</div>
    <div class="content">3) Pellentesque sagittis risus ac ante ultricies, ac convallis urna elementum.</div>
    <div class="content">4) Vivamus sodales aliquam massa quis lobortis. </div>
    <div class="content">5) Phasellus id sem sollicitudin lacus condimentum malesuada vel tincidunt neque.</div>
    <div class="content">6) Donec magna leo, rhoncus quis nunc eu, malesuada consectetur orci.</div>
    <div class="content">7) Praesent sollicitudin, quam a ullamcorper pharetra, urna lacus mollis sem, quis semper augue massa ac est.</div>
    <div class="content">8) Etiam leo magna, fermentum quis quam non, aliquam tincidunt erat.</div>
    <div class="content">9) Morbi pellentesque nibh nec nibh posuere, vel tempor magna dignissim.</div>
    <div class="content">10) In maximus fermentum elementum. Vestibulum ac lectus pretium, suscipit ante nec, bibendum erat.</div>
    <div class="content">11) Phasellus sit amet orci at lectus fermentum congue. Etiam faucibus scelerisque purus.</div>
    <div class="content">12) Pellentesque laoreet ipsum ac laoreet consectetur. </div>
    <div class="content">13) Integer aliquet odio magna, lobortis mattis tortor suscipit sed.</div>
    <div class="content">14) Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </div>
    <div class="content">15) Mauris a tellus luctus turpis elementum imperdiet vitae malesuada mauris. </div>
    <div class="content">16) Donec id libero sagittis, laoreet lorem vel, tempus nunc. </div>
    <div class="content">17) Donec vitae neque sed ex tristique hendrerit.</div>
    <div class="content">18) Aliquam sollicitudin gravida varius.</div>
    <div class="content">19) Donec auctor, augue sed finibus fermentum, neque erat interdum libero, eget porta metus lectus quis odio.</div>
    <div class="content">20) Nunc quis ante enim. Etiam nisl orci, hendrerit ut pretium nec, tempor in metus.</div>
    <div class="content">21) Donec et semper arcu.</div>
    <div class="content">22) Donec lobortis interdum purus, eu semper nisl pulvinar ac.</div>
    <div class="content">23) Cras laoreet eu elit vel porta.</div>
    <div class="content">24) Quisque pharetra arcu eget diam posuere commodo.</div>
    <div class="content">25) Nulla ornare eleifend neque, eget tincidunt nunc ullamcorper id. Nulla facilisi.</div>
</div>

【讨论】:

  • 谢谢。花了几个小时试图找到与我最初写的东西一起工作的东西,除了破坏它之外什么都做不了。我很感激。感谢您在笔记上做了出色的工作,因此我可以理解每件事的作用以及它与每个组件的关系。我还在学习,还有很长的路要走,但你的笔记对我学习很有帮助。
  • 如果我想在页面发生变化时让页面焦点在页面顶部,我会使用 .focus 函数并将其添加到 showpage 函数中吗?虽然自动对焦在台式机上不是问题,但在移动设备上是另一回事。
  • 太棒了,感谢 getPageList() 函数,正是我所需要的
  • 一个很好的解决方案。 “getPageList”是一个很棒的功能。它确实有助于使分页尽可能美观和优雅。
  • 就像一个魅力,谢谢男人
【解决方案2】:
                        <nav>
                        <ul class="pagination">
                            <!-- Lien vers la page précédente (désactivé si on se trouve sur la 1ère page) -->
                            <li class="page-item <?= ($currentPage == 1) ? "disabled" : "" ?>">
                                <a href="./winners.php?page=<?= 1 ?><?php echo $slink;?>" class="page-link">First</a>
                            </li>

                            <li class="page-item <?= ($currentPage == 1) ? "disabled" : "" ?>">
                                <a href="./winners.php?page=<?= $currentPage - 1 ?><?php echo $slink;?>" class="page-link"><i class="fad fa-chevron-double-left"></i></a>
                            </li>
                            <?php for($page = $currentPage-2; $page <= $currentPage+2; $page++): ?>
                                <!-- Lien vers chacune des pages (activé si on se trouve sur la page correspondante) -->
                                <?php if(($page > 0 )&&($page < $pages )) {?>
                                <li class="page-item <?= ($currentPage == $page) ? "active" : "" ?>">
                                    <a href="./winners.php?page=<?= $page ?><?php echo $slink;?>" class="page-link"><?= $page ?></a>
                                </li>
                                <?php }endfor ?>
                                <!-- Lien vers la page suivante (désactivé si on se trouve sur la dernière page) -->
                                <li class="page-item <?= ($currentPage == $pages) ? "disabled" : "" ?>">
                                <a href="./winners.php?page=<?= $currentPage + 1 ?><?php echo $slink;?>" class="page-link"><i class="fad fa-chevron-double-right"></i></a>
                            </li> 

                            <li class="page-item <?= ($currentPage == $pages) ? "disabled" : "" ?>">
                                <a href="./winners.php?page=<?= $pages ?><?php echo $slink;?>" class="page-link">Last</a>
                            </li>
                        </ul>
                        </nav>

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
相关资源
最近更新 更多