透過表單輸入行數、列數與儲存格內容(以 # 分隔),按鈕觸發 JS 動態建立 <table> 並插入頁面。示範 DOM 操作、字串解析、巢狀迴圈建立表格結構。
Trow(行)、Tcol(列)、Tv(內容字串)。Tv.split("#") 切割成陣列 a,第一列作為表頭 <th>,其後每 Tcol 個為一列 <tr>。Table1() 建立表頭與前幾列,tablevalue() 處理剩餘資料列。div#aa.innerHTML。<html>
<head>
<title>Js 動態生成表格</title>
<style> table { font-size:14px; } </style>
</head>
<body>
<script>
function tableclick(name1, name2, name3) {
var Trow = name1.value, Tcol = name2.value, Tv = name3.value;
if (!Trow || !Tcol || !Tv) { alert("請填寫完整條件"); return; }
Table1(parseInt(Trow), parseInt(Tcol), Tv);
}
function tablevalue(a, ai, rows, col, str) {
for (var i = 0; i < rows; i++) {
for (var j = 0; j < col; j++) {
if (j === 0 && ai >= a.length) break;
if (ai >= a.length) {
str += "<td> </td>";
} else {
if (j === 0) str += "<tr><th>" + a[ai++] + "</th>";
else str += "<td>" + a[ai++] + "</td>";
}
}
str += "</tr>";
}
return str;
}
function Table1(row, col, Str1) {
var str = "", a = Str1.split("#"), ai = 0;
str += "<table width='300' border='4'>";
// 表頭
for (var i = 0; i < col; i++) {
if (i === 0) str += "<tr><th>" + a[ai++] + "</th>";
else if (i === col - 1) str += "<th>" + a[ai++] + "</th></tr>";
else str += "<th>" + a[ai++] + "</th>";
}
// 資料列
if (a.length > col && row > 1) {
str = tablevalue(a, ai, row - 1, col, str);
}
str += "</table>";
document.getElementById("aa").innerHTML = str;
}
</script>
<form name="form1">
<p><b>行數:</b><input name="name1" type="text" style="width:40px" value="4">
<b>列數:</b><input name="name2" type="text" style="width:40px" value="4">
<input type="button" value="生成表格" onclick="tableclick(document.form1.name1, document.form1.name2, document.form1.name3)"></p>
<p><b>表值:</b></p>
<p><input name="name3" style="width:520px" value="COL1#COL2#COL3#COL4#ROW1#A1#A2#A3#ROW2#B1#B2#B3#ROW3#C1#C2#C3"></p>
</form>
<div id="aa"></div>
</body>
</html>
document.createElement 建立 DOM 節點替代字串拼接,避免 XSS 風險且效能更好。innerHTML。function generateTable(rows, cols, data) {
const container = document.getElementById('aa');
container.innerHTML = '';
const table = document.createElement('table');
table.border = 1;
const cells = data.split('#');
let idx = 0;
// thead
const thead = table.createTHead();
const hrow = thead.insertRow();
for (let c = 0; c < cols; c++) {
const th = document.createElement('th');
th.textContent = cells[idx++] || '';
hrow.appendChild(th);
}
// tbody
const tbody = table.createTBody();
for (let r = 1; r < rows; r++) {
const row = tbody.insertRow();
for (let c = 0; c < cols; c++) {
const td = row.insertCell();
td.textContent = cells[idx++] || '';
}
}
container.appendChild(table);
}