表格最後一行的輸入框被點擊 (焦點) 時,自動在底部複製新增一空白行,序號自動遞增,適合發票明細、費用報銷等動態列表錄入。
<!DOCTYPE html>
<html dir="ltr" lang="zh-TW">
<head>
<meta charset="UTF-8" />
<title>jQuery 動態新增表格列</title>
<style>
table { width:800px; margin:50px auto; border-collapse:collapse; border-spacing:0; }
table tr, table th, table td { border:1px solid #ddd; font-size:12px; }
table tr td:first-child { width:30px; text-align:center; }
table td input { width:100%; height:100%; padding:5px 0; border:0 none; box-sizing:border-box; }
table td input:focus { box-shadow:1px 1px 3px #ddd inset; outline:none; }
</style>
</head>
<body>
<table id="count">
<tr><th>序號</th><th>姓名</th><th>金額[USD]</th><th>時間</th><th>項目</th><th>單位</th><th>備註</th></tr>
<tr>
<td>1</td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function() {
var $table = $('#count');
var rowCount = 1;
var $lastRowTemplate = null;
// 事件委派:監聽表格內 input 的 focus 事件
$table.on('focus', 'input', function(e) {
var $target = $(e.target);
var $tr = $target.closest('tr');
// 只有最後一行觸發新增
if ($tr.index() === $table.find('tr').last().index()) {
rowCount++;
// 複製最後一行
var $newRow = $tr.clone();
// 更新序號
$newRow.find('td').eq(0).text(rowCount);
// 清空輸入框
$newRow.find('input').val('');
// 移除可能殘留的事件綁定 (clone(true) 會複製事件)
$table.append($newRow);
}
});
});
</script>
</body>
</html>
$table.on('focus', 'input', ...) 動態新增的行自動生效。$tr.index() === $table.find('tr').last().index()。$tr.clone() 保留結構與樣式,再修改序號、清空值。rowCount 計數器。$newRow.find('td:last').append('')$table.find('tr:gt(0)').map(...) 序列化為 JSON 送後端此模式廣泛應用於 ERP、CRM 等需動態增減明細列的企業級應用。