<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 動態表格增減行</title>
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }
.btn { margin: 2px; padding: 4px 8px; cursor: pointer; }
</style>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<button id="addRow" class="btn">添加一行</button>
<br><br>
<table id="dataTable">
<thead>
<tr><th>序號</th><th>名稱</th><th>數值</th><th>操作</th></tr>
</thead>
<tbody></tbody>
</table>
<script>
$(function() {
var rowIndex = 0;
// 添加行
$('#addRow').click(function() {
rowIndex++;
var html = '<tr>'
+ '<td>' + rowIndex + '</td>'
+ '<td><input type="text" placeholder="名稱"></td>'
+ '<td><input type="number" placeholder="數值"></td>'
+ '<td><button class="delRow btn">刪除</button></td>'
+ '</tr>';
$('#dataTable tbody').append(html);
});
// 刪除行(事件委託,支持動態添加的行)
$('#dataTable tbody').on('click', '.delRow', function() {
$(this).closest('tr').remove();
// 可選:重新排序序號
$('#dataTable tbody tr').each(function(i) {
$(this).find('td:first').text(i + 1);
});
});
});
</script>
</body>
</html>
複製上方代碼存為 `.html` 即可直接運行,實現表格行的動態增刪。