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

如何为表头居左的Bootstrap表格实现分页,及为指定Bootstrap表格添加每5条记录一页的分页功能

Great question! Since your table uses a row-based header (headers on the left, each column represents a single record), standard row-based pagination won't work here—we need to implement column-based pagination instead. Here's a step-by-step solution to add pagination that shows 5 records (columns) per page:


Step 1: Update the Table Structure

First, we'll add identifiers to make targeting elements easier, and wrap everything in a container for better Bootstrap styling:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

<div class="container mt-4">
  <!-- Add an ID to the table for easy selection -->
  <table id="vertical-header-table" class="table table-bordered">
    <tbody>
      <tr>
        <th>Row</th>
        <!-- Mark all record columns with a class -->
        <td class="record-column">1</td>
        <td class="record-column">2</td>
        <td class="record-column">3</td>
        <td class="record-column">4</td>
        <td class="record-column">5</td>
        <td class="record-column">6</td>
        <td class="record-column">7</td>
        <td class="record-column">8</td>
      </tr>
      <tr>
        <th>First Name</th>
        <td class="record-column">John</td>
        <td class="record-column">Peter</td>
        <td class="record-column">John</td>
        <td class="record-column">Alice</td>
        <td class="record-column">Bob</td>
        <td class="record-column">Charlie</td>
        <td class="record-column">Diana</td>
        <td class="record-column">Eve</td>
      </tr>
      <tr>
        <th>Last Name</th>
        <td class="record-column">Carter</td>
        <td class="record-column">Parker</td>
        <td class="record-column">Rambo</td>
        <td class="record-column">Smith</td>
        <td class="record-column">Jones</td>
        <td class="record-column">Brown</td>
        <td class="record-column">Williams</td>
        <td class="record-column">Miller</td>
      </tr>
      <tr>
        <th>Email</th>
        <td class="record-column">johncarter@mail.com</td>
        <td class="record-column">peterparker@mail.com</td>
        <td class="record-column">johnrambo@mail.com</td>
        <td class="record-column">alicesmith@mail.com</td>
        <td class="record-column">bobjones@mail.com</td>
        <td class="record-column">charliebrown@mail.com</td>
        <td class="record-column">dianawilliams@mail.com</td>
        <td class="record-column">evemillers@mail.com</td>
      </tr>
    </tbody>
  </table>

  <!-- Bootstrap pagination container -->
  <nav aria-label="Record pagination">
    <ul id="pagination-controls" class="pagination justify-content-center"></ul>
  </nav>
</div>

Step 2: Add Pagination Logic with jQuery

This script will handle calculating pages, generating pagination buttons, and toggling column visibility:

$(document).ready(function() {
  const $table = $('#vertical-header-table');
  const $recordColumns = $('.record-column');
  const recordsPerPage = 5; // Set to 5 records per page
  const totalRecords = $recordColumns.length;
  const totalPages = Math.ceil(totalRecords / recordsPerPage);
  const $pagination = $('#pagination-controls');

  // Show a specific page of records
  function showPage(pageNumber) {
    // Hide all record columns first
    $recordColumns.hide();
    // Calculate which columns to display
    const startIndex = (pageNumber - 1) * recordsPerPage;
    const endIndex = startIndex + recordsPerPage;
    // Show the target columns
    $recordColumns.slice(startIndex, endIndex).show();
    // Update active pagination button
    $('.page-item').removeClass('active');
    $(`.page-item[data-page="${pageNumber}"]`).addClass('active');
  }

  // Generate Bootstrap-style pagination buttons
  function generatePagination() {
    // Previous button
    $pagination.append(`<li class="page-item"><a class="page-link" href="#" data-page="prev">Previous</a></li>`);
    // Page number buttons
    for (let i = 1; i <= totalPages; i++) {
      const activeClass = i === 1 ? 'active' : '';
      $pagination.append(`<li class="page-item ${activeClass}" data-page="${i}"><a class="page-link" href="#">${i}</a></li>`);
    }
    // Next button
    $pagination.append(`<li class="page-item"><a class="page-link" href="#" data-page="next">Next</a></li>`);
  }

  // Handle pagination button clicks
  $pagination.on('click', '.page-link', function(e) {
    e.preventDefault();
    const action = $(this).data('page');
    let currentPage = parseInt($('.page-item.active').data('page'));

    // Update current page based on button clicked
    if (action === 'prev' && currentPage > 1) {
      currentPage--;
    } else if (action === 'next' && currentPage < totalPages) {
      currentPage++;
    } else if (!isNaN(action)) {
      currentPage = action;
    }

    showPage(currentPage);
  });

  // Initialize pagination and show first page
  generatePagination();
  showPage(1);
});

Step 3: Optional Styling (For Better UX)

Add this CSS to refine the table and pagination appearance:

.pagination .page-link {
  cursor: pointer;
}
.table th {
  white-space: nowrap; /* Prevent header text from wrapping */
  min-width: 120px;
}

How It Works

  • We mark all record columns with .record-column to easily target them for show/hide actions.
  • The showPage function calculates which columns to display based on the current page number and toggles their visibility.
  • The generatePagination function creates standard Bootstrap pagination controls, including previous/next buttons and page numbers.
  • Click events on pagination buttons trigger page switches, updating the visible columns and active button state.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 21:02:34