萬盛學電腦網

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

jQuery 表格列拖曳排序:上移、下移、置頂完整實作

前言

後台管理常需調整列表順序。本文示範純 jQuery 實作「上移、下移、置頂」按鈕操作,含淡入淡出視覺回饋,並說明 AJAX 持久化要點。

HTML 結構

<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>

jQuery 核心邏輯

$(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(',') });
  }
});

關鍵技巧

  • 使用事件代理 (`$table.on('click', '.btn', ...)`) 處理動態新增列。
  • `$tr.index()` 取得在 `tbody` 中的索引(不含 thead)。
  • `insertBefore()` / `insertAfter()` / `prepend()` 原生 DOM 移動,高效且保留事件綁定。
  • `fadeOut` 回呼中移動 DOM,再 `fadeIn`,避免視覺跳動。

進階:拖曳排序

若需滑鼠拖曳,建議使用專門庫:

  • SortableJS:零依賴、支援觸控、桌面、巢狀列表。
  • jQuery UI Sortable:舊專案相容。
  • @dnd-kit:React/Vue 現代首選。

總結

按鈕式排序邏輯簡單可靠,核心在於索引判斷與 DOM 移動 API。生產環境務必搭配 AJAX 持久化,並考慮樂觀鎖防止並發衝突。

copyright © 萬盛學電腦網 all rights reserved