萬盛學電腦網

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

jQuery 動態產生表格完整實作指南

動態產生表格是前端常見需求:後端回傳 JSON 資料、使用者新增列、分頁載入。本文提供 jQuery 完整實作模式,涵蓋建立、渲染、事件綁定、效能優化。

基礎建表函式

function createTable(data, options = {}) {
    const {
        container = '#tableContainer',
        columns = [],           // [{key:'name', label:'姓名', render: fn}]
        keyField = 'id',        // 主鍵欄位
        clickable = false,      // 整列可點擊
        onRowClick = null       // 點擊回調
    } = options;
    
    const $container = $(container).empty();
    const $table = $('').appendTo($container);
    const $thead = $('').appendTo($table);
    const $tbody = $('').appendTo($table);
    
    // 建立表頭
    if (columns.length) {
        const $headerRow = $('').appendTo($thead);
        columns.forEach(col => {
            $('').data('rowData', row).appendTo($tbody);
        
        if (clickable) $tr.addClass('clickable').css('cursor', 'pointer');
        
        columns.forEach(col => {
            const value = row[col.key];
            const $td = $('
').text(col.label).appendTo($headerRow); }); if (clickable) $('').text('操作').appendTo($headerRow); } // 建立資料列 data.forEach((row, rowIndex) => { const $tr = $('
').appendTo($tr); if (col.render) { col.render($td, value, row, rowIndex); } else { $td.text(value ?? ''); } }); if (clickable && onRowClick) { $tr.on('click', function(e) { if (!$(e.target).is('button,a,input,select')) { onRowClick($(this).data('rowData'), this); } }); } }); return $table; }

使用範例

const userData = [
    { id: 1, name: '張三', email: 'zhang@example.com', role: 'admin', status: 1 },
    { id: 2, name: '李四', email: 'li@example.com', role: 'user', status: 1 },
    { id: 3, name: '王五', email: 'wang@example.com', role: 'editor', status: 0 }
];

const columns = [
    { key: 'name', label: '姓名' },
    { key: 'email', label: 'Email' },
    { 
        key: 'role', 
        label: '角色',
        render: ($td, value) => {
            const badges = { admin: 'danger', user: 'secondary', editor: 'info' };
            $td.html(`${value}`);
        }
    },
    { 
        key: 'status', 
        label: '狀態',
        render: ($td, value) => {
            $td.html(value 
                ? '● 啟用' 
                : '○ 停用');
        }
    }
];

createTable(userData, {
    container: '#userTable',
    columns,
    clickable: true,
    onRowClick: (rowData) => {
        console.log('點擊列:', rowData);
        // 彈出編輯模態框等
    }
});

動態新增/刪除列

// 新增列(置頂)
function prependRow(tableSelector, rowData, columns) {
    const $tbody = $(tableSelector + ' tbody');
    const $tr = buildRow(rowData, columns).prependTo($tbody);
    // 重新套用奇偶行樣式(若用 CSS nth-child 則自動生效)
}

// 刪除列
function removeRow(tableSelector, keyField, keyValue) {
    $(tableSelector + ' tbody tr').filter(function() {
        return $(this).data('rowData')[keyField] == keyValue;
    }).remove();
}

// 更新列
function updateRow(tableSelector, keyField, keyValue, newData, columns) {
    const $tr = $(tableSelector + ' tbody tr').filter(function() {
        return $(this).data('rowData')[keyField] == keyValue;
    }).first();
    
    if ($tr.length) {
        const rowData = { ...$tr.data('rowData'), ...newData };
        $tr.data('rowData', rowData);
        columns.forEach((col, i) => {
            const $td = $tr.find('td').eq(i);
            if (col.render) col.render($td, rowData[col.key], rowData);
            else $td.text(rowData[col.key] ?? '');
        });
    }
}

大量資料效能優化

1. DocumentFragment 批次掛載

function createTableFast(data, columns) {
    const fragment = document.createDocumentFragment();
    const table = document.createElement('table');
    
    // 建立 thead
    const thead = table.createTHead();
    const hRow = thead.insertRow();
    columns.forEach(col => {
        const th = document.createElement('th');
        th.textContent = col.label;
        hRow.appendChild(th);
    });
    
    // 建立 tbody
    const tbody = table.createTBody();
    data.forEach(row => {
        const tr = tbody.insertRow();
        columns.forEach(col => {
            const td = tr.insertCell();
            td.textContent = row[col.key] ?? '';
        });
    });
    
    fragment.appendChild(table);
    document.getElementById('container').appendChild(fragment);
}

2. 虛擬滾動(大量資料必備)

// 只渲染可視區域 + 緩衝區
class VirtualTable {
    constructor(container, data, rowHeight = 40, buffer = 5) {
        this.data = data;
        this.rowHeight = rowHeight;
        this.buffer = buffer;
        this.container = $(container);
        this.init();
    }
    
    init() {
        this.container.css({ position: 'relative', overflow: 'auto' });
        this.wrapper = $('
').appendTo(this.container); this.table = $('').appendTo(this.wrapper); this.thead = $('').appendTo(this.table); this.tbody = $('').appendTo(this.table); this.container.on('scroll', () => this.render()); this.render(); } render() { const scrollTop = this.container.scrollTop(); const visibleCount = Math.ceil(this.container.height() / this.rowHeight); const start = Math.max(0, Math.floor(scrollTop / this.rowHeight) - this.buffer); const end = Math.min(this.data.length, start + visibleCount + 2 * this.buffer); this.wrapper.height(this.data.length * this.rowHeight); this.tbody.empty(); for (let i = start; i < end; i++) { const row = this.data[i]; const tr = $('').css('position', 'absolute') .css('top', i * this.rowHeight) .css('height', this.rowHeight) .appendTo(this.tbody); // 填充儲存格... } } }

完整 HTML 範例

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jQuery 動態表格</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="p-4">
    <div class="d-flex justify-content-between mb-3">
        <h3>使用者管理</h3>
        <button class="btn btn-primary" id="addBtn">新增使用者</button>
    </div>
    <div id="tableContainer"></div>

    <script>
        // 這裡放入上述 createTable 函式與使用範例
        // ...
    </script>
</body>
</html>

總結建議

  • 簡單場景:createTable 函式 + CSS nth-child 奇偶行
  • 需頻繁增刪改:維護資料陣列,重渲或局部更新
  • 資料 > 500 列:必須實作虛擬滾動
  • 複雜互動(排序、篩選、分頁):考慮 DataTables、AG Grid、TanStack Table 等成熟庫
  • 事件委派:用 tbody.on('click', 'tr', handler) 替代逐列綁定
copyright © 萬盛學電腦網 all rights reserved