本节内容:
jquery创建表格,在点击单元格时自动增加一行表格。
例子:
<!DOCTYPE html>
<html dir="ltr" lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>jQuery 表格自动增加-www.jb200.com</title>
<meta name="keywords" content="jQuery, 表格, table, 自动增加" />
<meta name="description" content="jQuery表格自动增加" />
<meta name="viewport" content="width=device-width" />
<meta name="copyright" content="imsole.net" />
<meta name="designer" content="sole" />
<meta name="publisher" content="imsole.net" />
<meta name="author" content="sole" />
<meta name="robots" content="all" />
<meta name="distribution" content="global" />
<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="/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
/* 这是一种方法,不是最好的办法,但容易理解
var oTable = $("#count"), oTr = '', oInput = '', eEle = '';
oTable.on('mouseover', function(){
oTr = oTable.find('tr').last();
oInput = oTr.find('input');
eEle = oTr.clone();
oInput.on('click', function(){
var parent = $(this).parents('tr');
if(oTr.index() == parent.index()){
oTable.append(eEle);
}
});
});
*/
//这是第二种方法,比较精简,需要对jquery很熟悉。
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>