jQuery动态增删tr例子
<html>
<head>
<script type="text/javascript" src="../jquery/jquery-2.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//取随机数
var a={}
function getNum(){
while(true){
var b = Math.round(Math.random()*100).toString().substr(0,2);
if(b.toString().length === 2 && a[b] === undefined){
return a[b]=b;
}
}
};
//给css 为shuzhi的td取随机数
$('.shuzhi').each(function(index) {
$(this).html(getNum());
});
//进行量数据相加
$(".heji").click(function(){
var b=$(this).attr("id").substr(4,1);
var sum=0;
if(b.toString()=="1"){
for(var i=0;i<2;i++){
sum+=parseFloat($(".shuzhi").eq(i).html().toString());
}
}else if(b.toString()=="2"){
for(var i=2;i<4;i++){
sum+=parseFloat($(".shuzhi").eq(i).html().toString());
}
}else{
for(var i=4;i<6;i++){
sum+=parseFloat($(".shuzhi").eq(i).html().toString());
}
}
//创建tr
var $tr=$("<tr class='.add' align='center'><td >合计:</td><td class='sum'>"+sum+"</td><td><input id='del' class='del' style='width:80px;' type='button' value='重置'/></td></tr>");
//删除先前动态生成的tr
$(".del").parents("tr").remove();
//增加tr到table上,绑定.del click事件
$tr.find(".del").click(deltr).end().appendTo($("#usertable"));
});
function deltr(){
$(this).parents("tr").remove();
//重新给css 为shuzhi的td取随机数
$('.shuzhi').each(function(index) {
$(this).html(getNum());
});
};
});
</script>
</head>
<body>
<div>
<table id="usertable" border="1" bordercolor="#000303" cellspacing="0" align="left" cellpadding="5">
<tr class="tt" align="center">
<td class="shuzhi" style="width:80px;"></td>
<td class="shuzhi" style="width:80px;"></td>
<td><input style="width:80px;" type="button" class="heji" id="heji1" value="相加"/></td>
</tr>
<tr align="center">
<td class="shuzhi"></td>
<td class="shuzhi"></td>
<td><input style="width:80px;" type="button" class="heji" id="heji2" value="相加"/></td>
</tr>
<tr align="center">
<td class="shuzhi"></td>
<td class="shuzhi"></td>
<td><input style="width:80px;" type="button" class="heji" id="heji3" value="相加"/></td>
</tr>
</table>
</div>
</body>
</html>