先看下效果图(帮助大家理解实现哪些功能):
先上Html代码:
<body>
<div class="center">
<a id="addbottom">添加一行到底部</a> <a id="addtop">添加一行到顶部</a>
<table border="1px" width="100%">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
css代码:
<style type="text/css">
.center{
margin-left:auto;
margin-right:auto;
width:600px;
margin-top:100px;
}
table{
border:1px solid #000;
border-collapse:collapse;
}
thead{
background-color:#C03;
color:#FFF;}
a{
cursor:pointer;}
</style>
jquery:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var i = 1;
$("#addbottom").click(function(){
$("<tr><td>"+i+"</td><td></td><td><a id='del'>删除此行</a> <a id='addup'>向上添加一行</a> <a id='adddown'>向下添加一行</a></td></tr>").appendTo($("tbody"));
i++;
});
$("#addtop").click(function(){
$("<tr><td>"+i+"</td><td></td><td><a id='del'>删除此行</a> <a id='addup'>向上添加一行</a> <a id='adddown'>向下添加一行</a></td></tr>").prependTo($("tbody"));
i++;
});
$("#del").live("click",function(){
$(this).parent("td").parent("tr").remove();
});
$("#addup").live("click",function(){
$(this).parent("td").parent("tr").before($("<tr><td>"+i+"</td><td></td><td><a id='del'>删除此行</a> <a id='addup'>向上添加一行</a> <a id='adddown'>向下添加一行</a></td></tr>"));
i++;
});
$("#adddown").live("click",function(){
alert("2");
$(this).parent("td").parent("tr").after("<tr><td>"+i+"</td><td></td><td><a id='del'>删除此行</a> <a id='addup'>向上添加一行</a> <a id='adddown'>向下添加一行</a></td></tr>")
i++;
});
});
</script>