js如何制作table
文章标签
js
在 javascript 中,创建表格需要:1. 创建 元素;2. 使用 和 创建表头;3. 使用 和 创建表体;4. 使用 创建单元格;5. 设置边框和间距。
如何在 JavaScript 中创建表格
在 JavaScript 中,可以通过创建
元素来创建表格。步骤:
创建表头
示例代码:
// 创建一个 3 行 3 列的表格const table = document.createElement("table");table.setAttribute("border", "1");table.setAttribute("cellspacing", "0");// 创建表头const thead = document.createElement("thead");const trHead = document.createElement("tr");const th1 = document.createElement("th");th1.innerText = "列标题 1";const th2 = document.createElement("th");th2.innerText = "列标题 2";const th3 = document.createElement("th");th3.innerText = "列标题 3";trHead.appendChild(th1);trHead.appendChild(th2);trHead.appendChild(th3);thead.appendChild(trHead);// 创建表体const tbody = document.createElement("tbody");for (let i = 1; i <p>以上代码会在页面中创建如下表格:</p>
列标题 1 | 列标题 2 | 列标题 3 |
---|---|---|
行 1,列 1 | 行 1,列 2 | 行 1,列 3 |
行 2,列 1 | 行 2,列 2 | 行 2,列 3 |
行 3,列 1 | 行 3,列 2 | 行 3,列 3 |