jQuery动态增删表格并进行表格内容修改

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>无标题文档</title>

<script type="text/javascript" src="../jquery/jquery-2.1.1.js"></script>

<script type="text/javascript">

$(document).ready(function(){

var a={}

var num1;

var num2;

var num3;

var num4;

//取随机数

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;

}

}

};

//添加表格

$("#aa").bind("click",function(){

num1=0;

num2=0;

num3=0;

num4=0;

num1+=parseFloat(getNum());

num2+=parseFloat(getNum());

num3+=parseFloat(getNum());

num4+=parseFloat(getNum());

var $add=$("<table id='table1' width='500' border='1'><tr><td id='num1' width='127'>"+num1+"</td><td id='num2' width='127'>"+num2+"</td><td width='120' id='heji1'>合计:</td><td width='100'><input style='width:80px;' class='add' id='add1' type='button' value='求和'></td></tr><tr><td id='num3'>"+num3+"</td><td id='num4'>"+num4+"</td><td id='heji2'>合计:</td><td><input style='width:80px;' class='add' id='add2' type='button' value='求和'></td></tr></table>");

//选定添加、否则删除

if(this.checked){

//动态添加click事件

$add.find(".add").click(qiuhe);

$("body").append($add);

}else{

$("body > table").remove();

}

});

$("#bb").bind("click",function(){

var $add=$("<div><img src='img/超神学院.jpg' width='300' height='200'>&nbsp<img src='img/海贼王.jpg' width='300' height='200'></div>");

//选定添加、否则删除

if(this.checked){

$("body").append($add);

}else{

$("body > div").remove();

}

});

//求和计算

function qiuhe(){

var b=$(this).attr("id").substr(3,1);

if(b=="1"){

var sum=0;

sum+=Number(num1);

sum+=Number(num2);

var $td=$("<td id='heji1' width='120'>合计:"+sum+"</td>");

$("#heji1").replaceWith($td);//替换td

}else{

var sum=0;

sum+=Number(num3);

sum+=Number(num4);

var $td=$("<td id='heji2' width='120'>合计:"+sum+"</td>");

$("#heji2").replaceWith($td);

}

   };

});

</script>

</head>

<body>

AA:<input name="" type="checkbox" value="" id="aa">

BB:<input name="" type="checkbox" value="" id="bb">

</body>

</html>

相关推荐