萬盛學電腦網

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

jQuery 實現可編輯表格:點擊單元格直接修改、Enter 確認、ESC 取消、無障礙支援

可編輯表格是後台管理、資料錄入系統的高頻需求。本文提供一個無依賴(僅 jQuery)、無障礙、支援鍵盤導航、輸入驗證、事件擴充的完整實作,並說明現代框架下的替代方案。

核心邏輯流程

  1. 點擊 <td> → 若已編輯中則忽略
  2. 記錄原始文字、建立 <input>、同步寬高樣式
  3. focus() + select() 方便使用者全選替換
  4. Enter → 驗證通過 → 更新單元格文字、觸發 cell:save 事件
  5. Escape → 恢復原文字、觸發 cell:cancel 事件
  6. 點擊外部/失焦 → 可選自動儲存或取消

完整實作(jQuery Plugin 模式)


(function($) {
  $.fn.editableTable = function(options = {}) {
    const opts = $.extend({
      selector: 'td.editable',      // 可編輯單元格選擇器
      inputClass: 'cell-editor',    // input 樣式類
      validate: null,               // function(value, $cell) => true/false 或 Promise
      onSave: null,                 // function(value, $cell, oldValue)
      onCancel: null,               // function($cell, oldValue)
      autoSaveOnBlur: false,        // 失焦自動儲存
      enterToSave: true,            // Enter 儲存
      escToCancel: true,            // ESC 取消
      tabNavigation: true           // Tab/Shift+Tab 導航
    }, options);

    return this.each(function() {
      const $table = $(this);
      let $currentInput = null;
      let $currentCell = null;
      let originalValue = '';

      // 事件委派:動態新增列也生效
      $table.on('click', opts.selector, function(e) {
        if ($currentInput) return; // 已有編輯中
        startEdit($(this));
      });

      function startEdit($cell) {
        $currentCell = $cell;
        originalValue = $cell.text();
        
        $currentInput = $('', {
          type: 'text',
          class: opts.inputClass,
          value: originalValue,
          css: {
            width: $cell.outerWidth(),
            height: $cell.outerHeight(),
            border: 'none',
            outline: 'none',
            font: 'inherit',
            padding: '2px 4px',
            boxSizing: 'border-box',
            background: '#fff'
          }
        }).appendTo($cell.empty())
          .trigger('focus')
          .trigger('select');

        // 鍵盤處理
        $currentInput.on('keydown', handleKeydown);
        // 失焦處理
        if (opts.autoSaveOnBlur) {
          $currentInput.on('blur', () => save());
        } else {
          $currentInput.on('blur', cancel);
        }
      }

      function handleKeydown(e) {
        if (e.key === 'Enter' && opts.enterToSave) {
          e.preventDefault();
          save();
        } else if (e.key === 'Escape' && opts.escToCancel) {
          cancel();
        } else if (e.key === 'Tab' && opts.tabNavigation) {
          e.preventDefault();
          save();
          navigate(e.shiftKey ? 'prev' : 'next');
        }
      }

      function save() {
        if (!$currentInput) return;
        const newValue = $currentInput.val();
        
        // 驗證
        if (opts.validate) {
          const result = opts.validate(newValue, $currentCell);
          if (result instanceof Promise) {
            result.then(valid => valid ? commit(newValue) : shake());
            return;
          }
          if (!result) return shake();
        }
        commit(newValue);
      }

      function commit(value) {
        $currentCell.text(value).data('original', value);
        opts.onSave?.(value, $currentCell, originalValue);
        cleanup();
      }

      function cancel() {
        if (!$currentCell) return;
        $currentCell.text(originalValue);
        opts.onCancel?.($currentCell, originalValue);
        cleanup();
      }

      function shake() {
        $currentInput.addClass('shake');
        setTimeout(() => $currentInput.removeClass('shake'), 300);
      }

      function navigate(dir) {
        const $cells = $table.find(opts.selector);
        const idx = $cells.index($currentCell);
        const nextIdx = dir === 'next' ? (idx + 1) % $cells.length : (idx - 1 + $cells.length) % $cells.length;
        $cells.eq(nextIdx).click();
      }

      function cleanup() {
        $currentInput.off('keydown blur').remove();
        $currentInput = null;
        $currentCell = null;
      }
    });
  };
})(jQuery);

// CSS 震動動畫
// .shake { animation: shake 0.3s; }
// @keyframes shake { 0%,100%{transform:translateX(0)} 25%{transform:translateX(-4px)} 75%{transform:translateX(4px)} }

使用範例


$('#dataTable').editableTable({
  selector: 'td[data-editable="true"]',
  validate: (val, $cell) => {
    if ($cell.data('type') === 'number' && isNaN(Number(val))) return false;
    if ($cell.data('required') && !val.trim()) return false;
    return true;
  },
  onSave: (val, $cell, old) => {
    console.log(`儲存: ${$cell.data('field')} = ${val}`);
    // AJAX 送後端
    $.post('/api/update', { id: $cell.closest('tr').data('id'), field: $cell.data('field'), value: val });
  },
  onCancel: ($cell, old) => console.log('取消編輯'),
  autoSaveOnBlur: true
});

HTML 結構範例


姓名年齡Email
小明 25 ming@example.com
小紅 28 hong@example.com

無障礙增強(ARIA)


// 在 startEdit 中加入
$currentCell.attr('aria-hidden', 'true');
$currentInput.attr({
  'role': 'textbox',
  'aria-label': `編輯 ${$currentCell.data('field') || '單元格'}`,
  'aria-describedby': 'edit-hint'
});

// 頁面加入隱藏提示
// 按 Enter 確認,Esc 取消,Tab 切換下一欄

現代框架替代方案

框架推薦方案特色
Vue 3自建指令 v-editable 或 vue3-editable響應式雙向綁定、TypeScript 支援
Reactreact-data-grid、@tanstack/react-table (v8+)虛擬滾動、列類型豐富、Headless 架構
Sveltesvelte-grid 或自建 action編譯時優化、體積極小
原生 Web Components@ionic/core 或自建 <editable-cell>框架無關、原生封裝

結語

jQuery 可編輯表格的核心在於事件委派、輸入元素生命週期管理、鍵盤交互、驗證擴充點。上述 Plugin 模式已涵蓋生產環境 90% 需求。新專案建議直接採用框架生態成熟的表格庫(TanStack Table, AG Grid, react-data-grid),避免重複造輪子;存量 jQuery 專案可直接複製上述代碼,並按需擴充下拉選單、日期選擇器、富文本編輯器等編輯器類型。

copyright © 萬盛學電腦網 all rights reserved