萬盛學電腦網

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

JavaScript 動態向表格追加行數據:DOM 操作實戰

點擊源表格行「新增」按鈕,將該行數據提取並追加到目標表格。演示 insertRow/insertCell 原生 DOM API 操作。

HTML 結構

<table id="srcTable" border="1">
  <tr><td>1</td><td><input value="20"><input value="200"></td><td>張三</td><td>備註</td><td><button onclick="addRow(this)">新增</button></td></tr>
  <!-- 更多行 -->
</table>

<table id="destTable" border="1">
  <tr><th>ID</th><th>年齡</th><th>金額</th><th>姓名</th></tr>
</table>

核心函數

function addRow(btn){
    // 1. 定位源行
    const row = btn.parentNode.parentNode;
    const srcTable = document.getElementById('srcTable');
    const rowIndex = row.rowIndex; // 自動獲取行索引

    // 2. 提取數據
    const cells = row.cells;
    const id = cells[0].innerText;
    const age = cells[1].children[0].value;
    const money = cells[1].children[1].value;
    const name = cells[2].innerText;

    // 3. 追加到目標表格
    const destTable = document.getElementById('destTable');
    const newRow = destTable.insertRow(); // 默認追加到末尾
    newRow.align = 'center';
    [id, age, money, name].forEach((val, i) => {
        const cell = newRow.insertCell(i);
        cell.innerHTML = val;
    });
}

關鍵 API

  • row.rowIndex:行在整個表格中的索引(含 thead)。
  • table.insertRow(index):插入行,省略參數則追加。
  • row.insertCell(index):插入單元格。
  • cell.innerHTML:設置內容,自動解析 HTML 字符串。

現代化寫法

function addRow(btn){
    const $row = $(btn).closest('tr');
    const data = [
        $row.find('td:eq(0)').text(),
        $row.find('td:eq(1) input:eq(0)').val(),
        $row.find('td:eq(1) input:eq(1)').val(),
        $row.find('td:eq(2)').text()
    ];
    $('#destTable').append(`<tr>${data.map(d => `<td>${d}</td>`).join('')}</tr>`);
}

jQuery 選擇器更簡潔,模板字符串拼接更直觀。大量操作時建議用 DocumentFragment 批量掛載。

copyright © 萬盛學電腦網 all rights reserved