You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML与JavaScript搜索结果分页:限制页码显示数量方案问询

Got it, let's fix that overflowing pagination issue! The goal is to only render a fixed range of page numbers (like 1-10, 11-20, etc.) instead of every single page, which gets messy with hundreds of results. Here's how to adapt your existing HTML/Razor and JavaScript code to implement this segmented pagination:

Step 1: Update the HTML/Razor Structure

First, replace the static @for loop that generates all pages with a dynamic container. We'll also add optional group navigation buttons (the "..." links) to jump between page segments:

<div class="row igs-learning-paths-pagination-row">
    <div class="col-12 d-flex justify-content-center">
        <ul class="pagination pagination-info">
            <li class="page-item">
                <a href="javascript:void(0)" onclick="displayPreviousPage()" class="igs-learning-paths-pagingation-text igs-text-uppercase">
                    @Umbraco.GetDictionaryValue("Common Prev", "Prev..").ToUpper()
                </a>
            </li>
            &nbsp;
            <!-- Dynamic pagination numbers container -->
            <li id="pagination-numbers-container" class="d-flex"></li>
            <!-- Group navigation buttons -->
            <li class="page-item" id="prev-group-item" style="display:none;">
                <a href="javascript:void(0)" onclick="goToPreviousGroup()" class="page-link">...</a>
            </li>
            <li class="page-item" id="next-group-item" style="display:none;">
                <a href="javascript:void(0)" onclick="goToNextGroup()" class="page-link">...</a>
            </li>
            &nbsp;
            <li class="page-item" alt="Go forward a page" title="Go forward a page">
                <a href="javascript:void(0)" alt="Go forward a page" title="Go forward a page" onclick="displayNextPage()" class="igs-learning-paths-pagingation-text igs-text-uppercase search-result-margin">
                    @Current.UmbracoHelper.GetDictionaryValue("Common Next", "Next..").ToUpper()
                </a>
            </li>
        </ul>
    </div>
</div>

Step 2: Rewrite the JavaScript for Dynamic Pagination

We'll add logic to generate only the current segment of pages, handle group navigation, and fix edge cases like incomplete last pages:

var numberPerPage = @numberPerPage;
var totalResults = @Model.Results.Count();
// Fix max page calculation (accounts for partial last pages)
var maxPage = Math.ceil(totalResults / numberPerPage) - 1;
var currentPage = 0;
var previousPage = 0;
// Define how many pages to show per segment (adjust this to your needs)
var pageRange = 10;

// Initialize pagination on load
generatePaginationNumbers();

function displayNextPage() {
    if (currentPage >= maxPage) return;
    currentPage++;
    displayPages(currentPage);
    generatePaginationNumbers(); // Refresh page numbers
}

function displayPreviousPage() {
    if (currentPage <= 0) return;
    currentPage--;
    displayPages(currentPage);
    generatePaginationNumbers(); // Refresh page numbers
}

function displayPages(pageToDisplay) {
    // Hide all results first
    $("[id^='pageId-']").hide();
    
    currentPage = pageToDisplay;
    var skip = pageToDisplay * numberPerPage;
    
    // Show results for the current page (stop if we exceed total results)
    for (var i = 0; i < numberPerPage; i++) {
        var resultId = skip + i + 1; // Match your pageId numbering
        if (resultId > totalResults) break;
        $("#pageId-" + resultId).show();
    }
    
    // Update active page styling
    if (previousPage !== null) {
        $("#page-list-item-" + previousPage).removeClass("active");
    }
    previousPage = currentPage;
    $("#page-list-item-" + currentPage).addClass("active");
}

function generatePaginationNumbers() {
    var container = $("#pagination-numbers-container");
    container.empty();
    
    // Calculate the start and end of the current page segment
    var startPage = Math.floor(currentPage / pageRange) * pageRange;
    var endPage = Math.min(startPage + pageRange - 1, maxPage);
    
    // Generate each page number in the current segment
    for (var i = startPage; i <= endPage; i++) {
        var pageLi = $("<li>")
            .addClass("page-item non-generate-page-item")
            .attr("id", "page-list-item-" + i)
            .css("border-radius", "16px");
        
        if (i === currentPage) {
            pageLi.addClass("active");
        }
        
        var pageLink = $("<a>")
            .addClass("page-link")
            .attr("id", "page-number-" + i)
            .attr("href", "javascript:void(0)")
            .text(i + 1)
            .click(function() {
                var targetPage = parseInt($(this).attr("id").replace("page-number-", ""));
                displayPages(targetPage);
                generatePaginationNumbers();
            });
        
        pageLi.append(pageLink);
        container.append(pageLi);
    }
    
    // Show/hide previous group button
    $("#prev-group-item").toggle(startPage > 0);
    // Show/hide next group button
    $("#next-group-item").toggle(endPage < maxPage);
}

function goToPreviousGroup() {
    var startPage = Math.floor(currentPage / pageRange) * pageRange;
    var targetPage = Math.max(startPage - pageRange, 0);
    displayPages(targetPage);
    generatePaginationNumbers();
}

function goToNextGroup() {
    var startPage = Math.floor(currentPage / pageRange) * pageRange;
    var targetPage = Math.min(startPage + pageRange, maxPage);
    displayPages(targetPage);
    generatePaginationNumbers();
}

Key Improvements Explained:

  • Dynamic Page Generation: Instead of rendering all pages upfront, we only generate the segment of pages the user is currently viewing (10 pages per segment by default).
  • Group Navigation: The "..." buttons let users jump between segments (e.g., from 1-10 to 11-20) without scrolling through hundreds of pages.
  • Edge Case Fixes: We corrected the maxPage calculation to account for partial last pages (e.g., 105 results with 10 per page = 11 total pages).
  • Active State Management: The active page styling updates automatically when switching pages or segments.

内容的提问来源于stack exchange,提问作者DarkW1nter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:47:48