本文示範一個實用的小工具:在網頁上輸入行數、列數與表值,按下按鈕就自動產生對應的表格。核心邏輯只有幾段 JavaScript,改成自己的資料格式後即可延伸出更多變化。
表值以 # 作為分隔字元傳入,程式先切成陣列,再依列數與行數把它填進 th 與 td 中。若數值不足以填滿整個表格,剩下的格子會以空白補齊,避免版面跑掉。
<html>
<head>
<title>Js 動態生成表格</title>
<style type="text/css">
table{font-size:14px;}
</style>
</head>
<body>
<script language="javascript">
function tableclick(name1, name2, name3){
Trow = name1.value;
Tcol = name2.value;
Tv = name3.value;
if ((Trow == "") || (Tcol == "") || (Tv == "")){
alert("請將制作表格的條件填寫完整");
} else {
r = parseInt(Trow);
c = parseInt(Tcol);
Table1(r, c, Tv);
}
}
function tablevalue(a, ai, rows, col, str){
int1 = a.length;
for (i = 0; i < rows; ++i){
for (j = 0; j < col; ++j){
if ((j == 0) && (ai >= int1)){ break; }
if (ai >= int1){
str = str + "<td scope='col'> </td>";
} else {
str = str + "<td scope='col'> " + (a[ai++]) + "</td>";
}
}
str = str + "</tr>";
}
return str;
}
function Table1(row, col, Str1){
var str = "";
a = new Array();
s = new String(Str1);
a = s.split("#");
int1 = a.length;
ai = 0;
if (col <= int1){
str = str + "<table width='300' border='4'>";
for (i = 0; i < col; ++i){
if (i == 0){
str = str + "<tr><th scope='col'> " + (a[ai++]) + "</th>";
} else if (i == (col - 1)){
str = str + "<th scope='col'> " + (a[ai++]) + "</th></tr>";
} else {
str = str + "<th scope='col'> " + (a[ai++]) + "</th>";
}
}
if (int1 > col){
if (row > 1){
str = tablevalue(a, ai, row - 1, col, str);
}
}
str = str + "</table>";
aa.innerHTML = str;
}
}
</script>
<form name="form1" method="post" action="">
<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" name="Submit3" value="生成表格"
onClick="tableclick(document.form1.name1, document.form1.name2, document.form1.name3)"></p>
<p><b align="top">表值:</b></p>
<p>
<input name="name3" wrap="VIRTUAL" 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>
這份程式用字串拼接組出 HTML,好處是直觀、無依賴;若要 production 使用,建議改用 document.createElement 建立節點,一方面避免 XSS 風險(表值若來自使用者輸入,直接寫進 innerHTML 是危險的),另一方面也更容易套用樣式與事件。此外,把資料來源從文字方塊換成陣列或 JSON,就能直接對接後端 API。