本文提供一個功能完整的 jQuery 表格排序與分頁插件式寫法,支援字母、數字、日期三種資料類型排序,並內建斑馬紋與分頁控制,可直接套用於後台管理列表等場景。
<th> 切換升序/降序(類別 .sorted-asc/.sorted-desc)。.sort-alpha(字串)、.sort-numeric(數值)、.sort-date(日期)。.odd/.even。$.fn.alternateRowColors = function() {
$('tbody tr:odd', this).removeClass('even').addClass('odd');
$('tbody tr:even', this).removeClass('odd').addClass('even');
return this;
};
$('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
});
}
});
$('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
});
<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>
<thead>、<tbody>,且需排序的欄位加上對應類別。