表單填寫時,常會需要讓使用者自行增加資料列,例如報帳明細。以下分享一個以 jQuery 動態複製並新增表格列的範例。
<!DOCTYPE html>
<html dir="ltr" lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>jQuery 表格自動增加</title>
<style type="text/css">
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; }
table td input:focus { box-shadow:1px 1px 3px #ddd inset; outline:none; }
</style>
<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" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
// 精簡寫法:點擊最後一列時,複製該列並遞增序號後附加
var oTable = $("#count"), iNum = 1, eEle = '';
oTable.on('click', function(e){
var target = e.target,
oTr = $(target).closest('tr');
if(oTr.index() == oTable.find('tr').last().index()){
iNum++;
eEle = oTr.clone();
eEle.find('td').eq(0).text(iNum);
}
oTable.append(eEle);
});
});
</script>
</body>
</html>
原理是監聽表格的點擊事件,判斷被點擊的是否為最後一列,若是就複製該列、更新序號後附加到表格尾端。透過 e.target 與 closest('tr') 找出所在列,是這裡的關鍵技巧。