後台管理常需調整列表順序。本文示範純 jQuery 實作「上移、下移、置頂」按鈕操作,含淡入淡出視覺回饋,並說明 AJAX 持久化要點。
<table class="table">
<thead>
<tr><th>標題</th><th>日期</th><th>操作</th></tr>
</thead>
<tbody>
<tr>
<td>HTML5 地理定位</td><td>2024-01-15</td>
<td>
<a href="#" class="move-up">上移</a>
<a href="#" class="move-down">下移</a>
<a href="#" class="move-top">置頂</a>
</td>
</tr>
<tr><td>CSS 固定頁腳</td><td>2024-01-10</td><td>...</td></tr>
<!-- 更多列 -->
</tbody>
</table>
$(function() {
const $table = $('.table tbody');
const $rows = () => $table.children('tr');
// 上移
$table.on('click', '.move-up', function(e) {
e.preventDefault();
const $tr = $(this).closest('tr');
const index = $tr.index();
if (index > 0) {
$tr.fadeOut(150, function() {
$tr.insertBefore($rows().eq(index - 1)).fadeIn(150);
persistOrder();
});
}
});
// 下移
$table.on('click', '.move-down', function(e) {
e.preventDefault();
const $tr = $(this).closest('tr');
const index = $tr.index();
const len = $rows().length;
if (index < len - 1) {
$tr.fadeOut(150, function() {
$tr.insertAfter($rows().eq(index + 1)).fadeIn(150);
persistOrder();
});
}
});
// 置頂
$table.on('click', '.move-top', function(e) {
e.preventDefault();
const $tr = $(this).closest('tr');
$tr.fadeOut(150, function() {
$table.prepend($tr).fadeIn(150);
$tr.css('color', '#f60'); // 視覺標記
persistOrder();
});
});
function persistOrder() {
const ids = $rows().map(function() { return $(this).data('id'); }).get();
// AJAX 送至後端
$.post('/api/reorder', { order: ids.join(',') });
}
});
若需滑鼠拖曳,建議使用專門庫:
按鈕式排序邏輯簡單可靠,核心在於索引判斷與 DOM 移動 API。生產環境務必搭配 AJAX 持久化,並考慮樂觀鎖防止並發衝突。