萬盛學電腦網

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

JavaScript 動態增刪表格行完整實現

核心功能

  • 點擊「增加一行」在表格末尾插入新行,包含複選框、序號、輸入框
  • 勾選複選框點擊「刪除一行」批量刪除選中行
  • 序號自動遞增

完整代碼

<html><head>
<script>
// 增加行
function addNewRow() {
    var tab = document.getElementById("myTab");
    var rows = tab.rows.length;
    var cols = tab.rows[rows - 1].cells.length;
    var newRow = tab.insertRow(rows);
    
    newRow.insertCell(0).innerHTML = 
        "<input type='checkbox' name='chkArr' id='chkArr" + rows + "' style='width:20px' />";
    newRow.insertCell(1).innerHTML = 
        "<input type='text' name='nodecode' id='nodecode" + rows + "' style='width:40px' value='" + rows + "'/>";
    newRow.insertCell(2).innerHTML = 
        "<input type='text' name='nodename' id='nodename" + rows + "' style='width:120px' />";
    newRow.insertCell(3).innerHTML = 
        "<input type='text' name='nodeper' id='nodeper" + rows + "' style='width:60px' />";
}

// 刪除勾選行
function removeRow() {
    var chks = document.getElementsByName("chkArr");
    var tab = document.getElementById("myTab");
    for (var k = 0; k < chks.length; k++) {
        if (chks[k].checked) {
            tab.deleteRow(k + 1); // +1 跳過表頭
            k = -1; // 重置索引,因集合即時更新
        }
    }
}
</script>
</head><body>
<input type="button" onclick="addNewRow()" value="增加一行" />
<input type="button" onclick="removeRow()" value="刪除一行" />
<table id="myTab" border="1" cellpadding="0" cellspacing="0" width="600">
    <tr>
        <th width="40">操作</th>
        <th width="40">序號</th>
        <th>節點名稱</th>
        <th width="80">節點比例</th>
    </tr>
</table>
</body></html>

關鍵技術點

  1. table.insertRow(index) / row.insertCell(index):DOM 表格專用 API,比拼接 HTML 字符串更標準
  2. deleteRow(index):直接操作表格 DOM 結構
  3. 索引重置技巧:刪除後 k = -1 配合 k++ 實現從頭重新檢查,因 HTMLCollection 是即時集合
  4. ID 唯一性:動態生成 id='chkArr' + rows 避免重複

現代化改進建議

  • 使用 template 標籤定義行模板,cloneNode(true) 複製
  • 事件委托綁定在 tbody 上,避免逐行綁定
  • 數據驅動視圖:維護數據陣列,重新渲染而非直接操作 DOM
copyright © 萬盛學電腦網 all rights reserved