HOWTO · JavaScript

使用 JavaScript 建立表格

在本文中,我們將看到如何藉助 JavaScript 建立表格。

本頁內容

使用 JavaScript 資料建立 HTML 表格時,可透過 document.createElement() 建立元素、以 textContent 設定儲存格文字,再用 appendChild() 將完成的表格加入頁面容器。當列資料會在頁面執行期間變動時,這種方式很實用。

HTML 表格結構與所需元素

表格使用巢狀元素來描述內容。table 元素包含列(tr);每列則包含標題儲存格(th)或資料儲存格(td)。使用 th 標示列或欄,使用 td 放置一般資料。標題儲存格不限於 thead,也可以用來標示表格主體中的列。

thead 和 tbody 分別用來分組標題列與主體列,能讓較大的表格更容易整理,但不是每個表格都必須使用。若表格需要摘要或頁尾列,也可以用 tfoot 分組。小型表格只要具備 table、列和儲存格即可;在分組元素能讓結構更清楚時,再加上這些元素。

使用 JavaScript 建立並填入表格

下方範例會建立一個標題列和兩個資料列,形成包含三欄的表格:編號、姓名和公司。每個儲存格都使用 textContent 放入一般文字。這會將值視為文字,而不是解析成 HTML;若資料可能包含使用者輸入,這是較安全的預設做法。

下方的瀏覽器範例使用原生 DOM,並將完成的表格加入既有的 #table-container。接著的獨立 Node.js 示範使用簡化的 DOM 模型呈現建立列的邏輯與計數;它不會建立可在瀏覽器中顯示的表格。

瀏覽器頁面範例(儲存為 HTML 頁面後,在瀏覽器中開啟):

本節中的程式碼以及顯示的標籤或輸出仍為英文。

<!doctype html>
<html lang="en">
  <body>
    <div id="table-container"></div>
    <script>
      const container = document.getElementById("table-container");
      const table = document.createElement("table");
      const thead = document.createElement("thead");
      const tbody = document.createElement("tbody");
      const headings = ["No.", "Name", "Company"];
      const records = [
        ["1", "James Clerk", "Netflix"],
        ["2", "Adam White", "Microsoft"]
      ];

      const headerRow = document.createElement("tr");
      for (const heading of headings) {
        const cell = document.createElement("th");
        cell.textContent = heading;
        headerRow.appendChild(cell);
      }
      thead.appendChild(headerRow);

      for (const record of records) {
        const row = document.createElement("tr");
        for (const value of record) {
          const cell = document.createElement("td");
          cell.textContent = value;
          row.appendChild(cell);
        }
        tbody.appendChild(row);
      }

      table.appendChild(thead);
      table.appendChild(tbody);
      container.appendChild(table);
    </script>
  </body>
</html>

執行以下獨立的 JavaScript 範例:

class Element {
  constructor(name) {
    this.name = name;
    this.children = [];
    this.textContent = "";
  }

  appendChild(child) {
    this.children.push(child);
    return child;
  }
}

const document = {
  createElement(name) {
    return new Element(name);
  },
  body: new Element("body")
};

const container = document.createElement("div");
container.id = "table-container";
document.body.appendChild(container);

const table = document.createElement("table");
const thead = document.createElement("thead");
const tbody = document.createElement("tbody");
const headings = ["No.", "Name", "Company"];
const records = [
  ["1", "James Clerk", "Netflix"],
  ["2", "Adam White", "Microsoft"]
];

const headerRow = document.createElement("tr");
for (const heading of headings) {
  const cell = document.createElement("th");
  cell.textContent = heading;
  headerRow.appendChild(cell);
}
thead.appendChild(headerRow);

for (const record of records) {
  const row = document.createElement("tr");
  for (const value of record) {
    const cell = document.createElement("td");
    cell.textContent = value;
    row.appendChild(cell);
  }
  tbody.appendChild(row);
}

table.appendChild(thead);
table.appendChild(tbody);
container.appendChild(table);

const tableElement = container.children[0];
const headerCells = tableElement.children[0].children[0].children;
const bodyRows = tableElement.children[1].children;
console.log(`${headerCells.length} headings, ${bodyRows.length} data rows`);
3 headings, 2 data rows

document.createElement() 接受字串形式的元素名稱,並傳回新的元素。程式碼會為每一列建立一個 tr,再加入 th 或 td 儲存格。每個儲存格填入內容後,才會將該列放入 thead 或 tbody。最後,把這些分組放入表格,再將表格附加至範例開頭建立的容器。

若頁面由你管理,容器可以簡單寫成 <div id="table-container"></div>。在瀏覽器程式碼中,使用 document.getElementById("table-container") 選取這個既有元素,再將完成的表格附加至其中。請將指令碼放在頁面容器之後,或等文件載入完成後再執行,確保目標元素已存在。外觀請另外使用 CSS 設定,例如為 table、th 和 td 加上框線與內距;JavaScript 負責建立結構和內容,CSS 則控制呈現方式。

將表格附加至 DOM 並確認結果

使用 container.appendChild(table) 將完成的表格附加至選取的容器。這會把表格加入容器內,頁面其他內容則維持原狀。若要用表格取代既有內容,請先明確清除那些內容;否則每次執行都會再新增一個表格。

若要確認結果,請開啟瀏覽器開發人員工具,並在 Elements 面板檢查容器。容器中應有一個 table:thead 包含一列、其中有三個 th 儲存格;tbody 則包含兩列,每列各有三個 td 儲存格。呈現出的表格會顯示「No.」、「Name」和「Company」這些英文標題,下方列出 James Clerk / Netflix 和 Adam White / Microsoft。這些範例標籤與資料維持英文,因為程式碼區塊必須逐位元組保留。如果表格沒有出現,請確認容器 ID 和指令碼執行時機。一般文字值請繼續使用 textContent,不要將資料指定給 innerHTML。