展示兩種 JavaScript 動態操作 HTML 表格的方式:一是封裝物件導向的 InsterCell 建構函數,二是直接操作 DOM 的 insertRow()/insertCell() 方法。適用於發票明細、動態表單等場景。
<script>
function InsterCell(tableId, content, place) {
this.mTableId = document.getElementById(tableId);
this.mInsContent = content;
this.mInsPlace = place;
this.cInsCell = InsCell;
this.cClearCell = ClearCell;
}
function InsCell() {
var cell = this.mTableId.rows[0].cells[this.mInsPlace];
cell.innerHTML = '<table cellspacing="0" cellpadding="0" border="0"><tr>'
+ this.mInsContent
+ '</tr></table>';
this.mInsPlace++;
}
function ClearCell() {
for (var i = 0; i < this.mTableId.rows[0].cells.length / 2 - 1; i++) {
this.mTableId.rows[0].cells[2 * i + 1].innerHTML = "";
}
}
// 使用範例
var str = '<TD>交行原余額</TD><TD><input name="earning"></TD>'
+ '<TD><input name="payout"></TD><TD><input name="cashOnHand"></TD>'
+ '<TD><input name="cashOnHandRemark"></TD>';
var ins = new InsterCell("t1", str, 1);
ins.cInsCell();
</script>
<script>
function tbladdrow() {
var table = document.getElementById('Table1');
var i = table.rows.length;
var row = table.insertRow(-1); // 末尾插入
var col = row.insertCell(0);
col.innerHTML = '<INPUT id="line[' + i + '][Commcd]" name="line[' + i + '][Commcd]">';
// 可續加 insertCell(1), insertCell(2)...
}
</script>
<table id="Table1"><tr><td>標題</td></tr></table>
<button onclick="tbladdrow()">新增列</button>
document.getElementById + insertRow/insertCell,相容性佳、程式碼簡潔。eval() 與 innerHTML 拼接複雜結構,易產生 XSS 風險與維護困難。name 屬性建議採用陣列格式 name="field[]" 或 name="row[idx][field]",方便後端 $_POST 接收。