萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現表格本地排序與分頁完整範例

本文提供一個功能完整的 jQuery 表格排序與分頁插件式寫法,支援字母、數字、日期三種資料類型排序,並內建斑馬紋與分頁控制,可直接套用於後台管理列表等場景。

核心功能

  • 點擊表頭 <th> 切換升序/降序(類別 .sorted-asc/.sorted-desc)。
  • 自動偵測排序鍵:.sort-alpha(字串)、.sort-numeric(數值)、.sort-date(日期)。
  • 排序後自動重新套用奇偶列類別 .odd/.even。
  • 內建分頁:每頁 10 列,產生頁碼按鈕,支援跳頁。

關鍵程式碼片段

1. 斑馬紋插件化

$.fn.alternateRowColors = function() {
    $('tbody tr:odd', this).removeClass('even').addClass('odd');
    $('tbody tr:even', this).removeClass('odd').addClass('even');
    return this;
};

2. 排序邏輯

$('th', $table).each(function(column) {
    var findSortKey;
    if ($(this).is('.sort-alpha')) {
        findSortKey = function($cell) { return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase(); };
    } else if ($(this).is('.sort-numeric')) {
        findSortKey = function($cell) { var key = parseFloat($cell.text().replace(/^[^\d.]*/, '')); return isNaN(key) ? 0 : key; };
    } else if ($(this).is('.sort-date')) {
        findSortKey = function($cell) { return Date.parse('1 ' + $cell.text()); };
    }
    if (findSortKey) {
        $(this).addClass('clickable').hover(...).click(function() {
            // 切換排序方向、取得 rows 陣列、計算 sortKey、排序、重新 append、更新類別、觸發 repaginate
        });
    }
});

3. 分頁邏輯

$('table.paginated').each(function() {
    var currentPage = 0, numPerPage = 10, $table = $(this);
    $table.bind('repaginate', function() {
        $table.find('tbody tr').hide().slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show();
    });
    // 產生頁碼按鈕綁定 click 切換 currentPage 並觸發 repaginate
});

HTML 結構範例

<table class="myTable paginated">
  <thead>
    <tr>
      <th class="sort-alpha">Last Name</th>
      <th class="sort-alpha">First Name</th>
      <th>Email</th>
      <th class="sort-numeric">Due</th>
      <th class="sort-date">Date</th>
      <th>Web Site</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>Smith</td><td>John</td><td>jsmith@gmail.com</td><td>$50.00</td><td>Mar 2009</td><td>https://www.jb51.net</td></tr>
    ...
  </tbody>
</table>

使用建議

  1. 引入 jQuery 1.3.2+(範例用 1.3.2,現代專案建議 3.x)。
  2. 表格必須包含 <thead>、<tbody>,且需排序的欄位加上對應類別。
  3. 若資料量極大(超過數千列),建議改用伺服器端排序分頁或虛擬滾動方案。
copyright © 萬盛學電腦網 all rights reserved