萬盛學電腦網

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

JavaScript 動態生成表格:點擊按鈕新增單元格實現

功能演示

點擊頁面按鈕,即時在文檔中插入一個帶藍色背景、邊框的 100×100 像素表格,包含一行一列。此為早期原生 DOM 操作教學範例。

核心代碼

function creates() {
    // 創建 table 元素
    var newiframes = document.createElement("TABLE");
    newiframes.id = "t1";
    newiframes.width = "100";
    newiframes.border = "1";
    newiframes.height = "100";
    newiframes.align = "left";
    newiframes.style.background = "blue";

    // 插入行與儲存格
    newiframes.insertRow();
    newiframes.rows[0].insertCell();

    // 插入到 body 前
    document.body.insertBefore(newiframes);
}

代碼解析與改進點

  • 屬性設置:建議改用 setAttribute 或直接操作 DOM 屬性(如 newiframes.style.width = '100px')。
  • 插入位置:insertBefore 需要參考節點,原碼缺少第二參數,實際會報錯。應改為 document.body.appendChild(newiframes) 或指定參考節點。
  • ID 衝突:重複點擊會產生相同 id="t1",導致無效 HTML。應動態生成唯一 ID。
  • 語義化:<table> 應包含 <tbody>,現代瀏覽器會自動補全但最好顯式創建。

現代寫法範例

function addTable() {
    const table = document.createElement('table');
    table.style.cssText = 'width:100px;height:100px;border:1px solid #000;background:blue;margin:5px;';
    const tbody = document.createElement('tbody');
    const tr = document.createElement('tr');
    const td = document.createElement('td');
    tr.appendChild(td);
    tbody.appendChild(tr);
    table.appendChild(tbody);
    document.body.appendChild(table);
}
copyright © 萬盛學電腦網 all rights reserved