DIV CSS 佈局教程網

jQuery 表格本機排序與分頁實作解析
編輯:JavaScript綜合知識     

資料量不大、又不想每次排序都打伺服器時,直接在瀏覽器裡排序是最快的方案。這個範例做了四件事:點表頭排序、支援字母/數字/日期三種型別、雙向切換、以及排序後的隔行變色與分頁維護。

排序外掛的核心

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

$('table.myTable').each(function () {
  var $table = $(this);
  $table.alternateRowColors($table);

  $('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(function () { $(this).addClass('hover'); },
               function () { $(this).removeClass('hover'); })
        .click(function () {

          // 反向排序狀態
          var newDirection = 1;
          if ($(this).is('.sorted-asc')) newDirection = -1;

          var rows = $table.find('tbody>tr').get();   // 轉為原生陣列
          $.each(rows, function (index, row) {
            row.sortKey = findSortKey($(row).children('td').eq(column));
          });

          rows.sort(function (a, b) {
            if (a.sortKey < b.sortKey) return -newDirection;
            if (a.sortKey > b.sortKey) return newDirection;
            return 0;
          });

          $.each(rows, function (index, row) {
            $table.children('tbody').append(row);
            row.sortKey = null;
          });

          $table.find('th').removeClass('sorted-asc').removeClass('sorted-desc');
          var $sortHead = $table.find('th').filter(':nth-child(' + (column + 1) + ')');
          $sortHead.addClass(newDirection == 1 ? 'sorted-asc' : 'sorted-desc');

          $table.alternateRowColors($table);
          $table.find('td').removeClass('sorted')
                 .filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
          $table.trigger('repaginate');
        });
    }
  });
});

設計重點

用 class 宣告排序型別

表頭上掛 .sort-alpha、.sort-numeric、.sort-date 決定排序規則,不必為每欄寫 if-else。要新增型別(例如 IP、金額)只要再加一個分支,擴充成本很低。

sortKey 掛在 row 上

把排序鍵暫存在 DOM 元素物件上,sort 完成後再清空。這樣不必反覆讀取 cell 內容,排序過程中只算一次鍵值。

反向排序的判斷

檢查表頭目前是否帶 .sorted-asc:是則這次反向(-1),否則正向(1)。同時用 asc/desc 兩個 class 驅動箭頭樣式,視覺狀態與資料狀態保持一致。

排序後要重跑副作用的函式

$table.trigger('repaginate') 是關鍵:DOM 順序變了,分頁的 slice 範圍必須重新計算,隔行變色也要重套。把這些集中成事件,是避免「排序後顏色亂掉」的正確做法。

分頁部分

$('table.paginated').each(function () {
  var currentPage = 0;
  var numPerPage = 10;
  var $table = $(this);

  $table.bind('repaginate', function () {
    $table.find('tbody tr').hide()
      .slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show();
  });

  var numRows = $table.find('tbody tr').length;
  var numPages = Math.ceil(numRows / numPerPage);
  var $pager = $('<div class="pager"></div>');

  for (var page = 0; page < numPages; page++) {
    $('<span class="page-number"></span>').text(page + 1)
      .bind('click', { newPage: page }, function (event) {
        currentPage = event.data['newPage'];
        $table.trigger('repaginate');
        $(this).addClass('active').siblings().removeClass('active');
      })
      .appendTo($pager).addClass('clickable');
  }

  $pager.insertBefore($table);
  $table.trigger('repaginate');
  $pager.find('span.page-number:first').addClass('active');
});

分頁用 hide/show 搭配 slice,並監聽 repaginate 事件重算範圍,與排序邏輯自然解耦。

表格標記

<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>john@gmail.com</td><td>$50.00</td>
      <td>Mar 2009</td><td>https://www.jb51.net</td>
    </tr>
    <!-- 其餘資料列結構相同 -->
  </tbody>
</table>

兩個實務提醒

數字排序分支的 replace(/^[^d.]*/, '') 原意是去掉「非數字」字元,但字元類別中的 d 漏了反斜線,實際上並不會移除 $ 這類符號,導致 parseFloat("$50.00") 得到 NaN 而被一律當成 0。正確應為 /[^\d.]/g。

另外,日期排序用 Date.parse('1 ' + $cell.text()) 依賴瀏覽器對日期字串的解析,不同環境結果可能不一致。資料稍一變多,建議把日期統一成 ISO 8601(YYYY-MM-DD)格式,字典序即等於時間序,連解析都不必做。最後,純 hide/show 的分頁在資料量大時會一次渲染全部 DOM,若列數破千,應改為真正的資料切片或引入虛擬滾動。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved