萬盛學電腦網

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

JavaScript 動態新增/刪除 Table 列(TR)完整實作

功能需求

  • 動態新增一列輸入欄位(姓名、Email、電話、手機、公司)
  • 每列附「刪除」按鈕
  • 「清空」按鈕一次移除所有資料列
  • 自動維護流水號

現代化重構版(ES6+、無 jQuery 依賴)

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>動態 Table 範例</title>
<style>
table { border-collapse: collapse; width: 100%; max-width: 800px; margin: 1rem auto; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }
th { background: #007bff; color: #fff; }
input { width: 90%; padding: 4px; box-sizing: border-box; }
.btn { margin-right: 8px; padding: 6px 12px; cursor: pointer; }
.btn-danger { background: #dc3545; color: #fff; border: none; border-radius: 3px; }
.btn-primary { background: #007bff; color: #fff; border: none; border-radius: 3px; }
.btn-secondary { background: #6c757d; color: #fff; border: none; border-radius: 3px; }
</style>
</head>
<body>

<table id="signTable">
    <thead>
        <tr>
            <th style="width:50px;">序號</th>
            <th>姓名</th>
            <th>Email</th>
            <th>電話</th>
            <th>手機</th>
            <th>公司</th>
            <th style="width:80px;">操作</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

<div style="text-align:center; max-width:800px; margin:1rem auto;">
    <button class="btn btn-primary" id="btnAdd">+ 新增參與人</button>
    <button class="btn btn-secondary" id="btnClear">清空全部</button>
</div>

<script>
(() => {
    const tbody = document.querySelector('#signTable tbody');
    const btnAdd = document.getElementById('btnAdd');
    const btnClear = document.getElementById('btnClear');
    let rowIndex = 0; // 內部流水號

    // 建立單列 HTML
    function createRow(index) {
        const tr = document.createElement('tr');
        tr.dataset.index = index;
        tr.innerHTML = `
            <td>${index}</td>
            <td><input type="text" name="name_${index}" placeholder="姓名"></td>
            <td><input type="email" name="email_${index}" placeholder="email@example.com"></td>
            <td><input type="tel" name="tel_${index}" placeholder="市話"></td>
            <td><input type="tel" name="mobile_${index}" placeholder="手機"></td>
            <td><input type="text" name="company_${index}" placeholder="公司名稱"></td>
            <td><button class="btn btn-danger btn-del" data-index="${index}">刪除</button></td>
        `;
        return tr;
    }

    // 重新編號所有列
    function reindex() {
        [...tbody.rows].forEach((tr, i) => {
            const newIdx = i + 1;
            tr.dataset.index = newIdx;
            tr.cells[0].textContent = newIdx;
            // 更新 input name(若後端需依 name 接收)
            tr.querySelectorAll('input').forEach((inp, j) => {
                const prefixes = ['name','email','tel','mobile','company'];
                inp.name = `${prefixes[j]}_${newIdx}`;
            });
            tr.querySelector('.btn-del').dataset.index = newIdx;
        });
        rowIndex = tbody.rows.length;
    }

    // 新增
    function addRow() {
        rowIndex++;
        tbody.appendChild(createRow(rowIndex));
    }

    // 刪除單列(事件代理)
    tbody.addEventListener('click', e => {
        if (e.target.matches('.btn-del')) {
            e.target.closest('tr').remove();
            reindex();
        }
    });

    // 清空
    btnClear.addEventListener('click', () => {
        if (confirm('確定清空所有參與人?')) {
            tbody.innerHTML = '';
            rowIndex = 0;
            addRow(); // 保留一空列
        }
    });

    btnAdd.addEventListener('click', addRow);

    // 初始化一空列
    addRow();
})();
</script>
</body>
</html>

關鍵設計點解析

  1. 事件代理:在 tbody 掛單一 click 監聽,透過 e.target.matches('.btn-del') 判斷,避免逐列綁定、記憶體洩漏。
  2. data-index:儲存流水號於 dataset,不依賴 DOM 位置,刪除後重新編號更穩健。
  3. 重新編號函式:集中處理序號、name 屬性、按鈕 data-index,確保表單提交時後端能正確解析陣列。
  4. 模板字面值:ES6 \`...\` 產生 HTML,可讀性遠勝字串拼接。

原始舊碼問題對照

舊碼問題現代寫法改善
用 insertRow/insertCell 逐格建立innerHTML 或 createElement 批次建立
全域函式汙染 windowIIFE (()=>{...})() 封裝作用域
findObj 兼容 IE4 層層查找document.getElementById / querySelector 現代標準
刪除按鈕 href='#' + rowID + ')' 語法錯誤button + data-index + 事件代理
無 thead/tbody 語意結構補全語意標籤,利於無障礙與 CSS

後端接收建議

表單提交時,後端可依 name_1, email_1...name_N 解析,或改用陣列命名 name="users[1][name]" 配合框架自動綁定。

copyright © 萬盛學電腦網 all rights reserved