表格資料的前端排序操作 (上移、下移、置頂、拖曳) 是後台管理系統、CMS 內容管理、待辦事項等應用的高頻需求。本文提供一個功能完整、程式碼精簡、易於擴充的 jQuery 實作方案,並解析關鍵技術細節。
<table class="table table-sortable">
<thead>
<tr>
<th>標題</th>
<th>日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr data-id="1">
<td>HTML5 地理定位</td>
<td>2015-04-25</td>
<td class="actions">
<button type="button" class="btn-move-up">↑ 上移</button>
<button type="button" class="btn-move-down">↓ 下移</button>
<button type="button" class="btn-move-top">⬆ 置頂</button>
</td>
</tr>
<!-- 更多列 -->
</tbody>
</table>
<!-- 取得排序後的 ID 陣列按鈕 -->
<button id="get-order" type="button">取得排序結果</button>
;(function($) {
$.fn.tableRowSorter = function(options) {
const settings = $.extend({
rowSelector: 'tbody tr',
upBtn: '.btn-move-up',
downBtn: '.btn-move-down',
topBtn: '.btn-move-top',
animationDuration: 200,
onOrderChange: null // 回呼: function(newOrderArray)
}, options);
const $table = this;
const $rows = $table.find(settings.rowSelector);
const $upBtns = $table.find(settings.upBtn);
const $downBtns = $table.find(settings.downBtn);
const $topBtns = $table.find(settings.topBtn);
// 綁定事件 (使用事件委派支援動態新增列)
$table.on('click', settings.upBtn, function() {
const $row = $(this).closest('tr');
moveRow($row, 'up');
}).on('click', settings.downBtn, function() {
const $row = $(this).closest('tr');
moveRow($row, 'down');
}).on('click', settings.topBtn, function() {
const $row = $(this).closest('tr');
moveRow($row, 'top');
});
function moveRow($row, direction) {
const index = $row.index();
const $rows = $table.find(settings.rowSelector);
const total = $rows.length;
let $targetRow;
let animationProps = {};
switch (direction) {
case 'up':
if (index === 0) return; // 已是第一列
$targetRow = $rows.eq(index - 1);
// 視覺動畫:淡出淡入 + 位移
$row.fadeOut(settings.animationDuration).fadeIn(settings.animationDuration);
$targetRow.before($row.detach());
break;
case 'down':
if (index === total - 1) return; // 已是最後一列
$targetRow = $rows.eq(index + 1);
$row.fadeOut(settings.animationDuration).fadeIn(settings.animationDuration);
$targetRow.after($row.detach());
break;
case 'top':
if (index === 0) return;
$row.fadeOut(settings.animationDuration).fadeIn(settings.animationDuration);
$table.find('tbody').prepend($row.detach());
// 可選:置頂後高亮提示
$row.addClass('highlight-top').delay(1000).queue(function(next) {
$(this).removeClass('highlight-top');
next();
});
break;
}
// 觸發順序變更回呼
if ($.isFunction(settings.onOrderChange)) {
const newOrder = getCurrentOrder();
settings.onOrderChange(newOrder);
}
}
// 取得目前排序 (依 data-id)
function getCurrentOrder() {
return $table.find(settings.rowSelector).map(function() {
return $(this).data('id');
}).get();
}
// 公開方法:供外部呼叫取得順序
$table.data('tableRowSorter', {
getOrder: getCurrentOrder,
moveRow: moveRow
});
return this;
};
})(jQuery);
$(function() {
// 初始化
$('.table-sortable').tableRowSorter({
onOrderChange: function(newOrder) {
console.log('新排序:', newOrder); // [3, 1, 4, 2]
// 這裡可直接 AJAX 送往後端
saveOrderToServer(newOrder);
}
});
// 手動取得順序 (如儲存按鈕)
$('#get-order').on('click', function() {
const sorter = $('.table-sortable').data('tableRowSorter');
if (sorter) {
const order = sorter.getOrder();
alert('目前順序: ' + order.join(', '));
saveOrderToServer(order);
}
});
// 後端同步範例
function saveOrderToServer(orderArray) {
$.ajax({
url: '/api/table/reorder',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ order: orderArray }),
success: function(res) {
showToast('排序已儲存');
},
error: function() {
showToast('儲存失敗,請重試', 'error');
// 可選:回滾 UI 到伺服器狀態
}
});
}
});
若需支援滑鼠拖曳排序,建議整合 SortableJS (無依賴、輕量、觸控支援佳):
// 引入 SortableJS 後
const sortable = new Sortable(document.querySelector('.table-sortable tbody'), {
animation: 150,
handle: '.drag-handle', // 指定拖曳把手
onEnd: function(evt) {
const newOrder = $('.table-sortable').tableRowSorter('getOrder');
saveOrderToServer(newOrder);
}
});
.table-sortable tbody tr {
transition: background-color 0.2s;
}
.table-sortable tbody tr:hover {
background-color: #f8f9fa;
}
.table-sortable .highlight-top {
background-color: #fff3cd !important; // 置頂後暫時高亮
}
.table-sortable .actions {
white-space: nowrap;
}
.table-sortable .actions button {
margin-right: 4px;
padding: 2px 8px;
font-size: 0.85em;
}
.table-sortable .actions button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
function updateButtonStates($table, settings) {
const $rows = $table.find(settings.rowSelector);
$rows.each(function(i) {
const $row = $(this);
$row.find(settings.upBtn).prop('disabled', i === 0);
$row.find(settings.downBtn).prop('disabled', i === $rows.length - 1);
$row.find(settings.topBtn).prop('disabled', i === 0);
});
}
// 在 moveRow 完成後呼叫
updateButtonStates($table, settings);
表格列排序功能的核心在於 DOM 節點移動 (detach/prepend/before/after) 與 資料順序同步。封裝為 jQuery Plugin 並暴露 getOrder() 方法,能滿足多數專案需求。若專案需求較複雜 (多層巢狀、跨表格拖曳、虛擬滾動),建議直接採用成熟庫如 SortableJS 或 React/Vue 生態中的對應元件。