web前端实现JQuery对表格实时的编辑、增加和删除。
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<title></title>
<script src=”http://code.jquery.com/jquery-2.0.0.min.js”></script>
</head>
<body>
<input type=”text” name=”t1″ id=”t1″ placeholder=”请输入rows” style=”height: 30px;”/>
<input type=”text” name=”t2″ id=”t2″ placeholder=”请输入cols” style=”height: 30px;”/>
<input type=”button” name=”b1″ id=”b1″ value=”生成表格” style=”height: 30px;”/>
<div></div>
<script type=”text/javascript”>$(“div”).append(“<table></table>”);
$(“input[name=’b1′]”).click(function(){
$(“table”).html(“”).css(“borderCollapse”,”collapse”)
var rows=$(“#t1”).val();
var cols=$(“#t2”).val();
for(var i=0;i<rows;i++){
$(“table”).append(“<tr></tr>”);
}
for(var i=0;i<cols;i++){
$(“tr”).append(“<td></td>”);
}
$(“td”).css({width:”150px”,height:”40px”,border:” 1px solid black”,textAlign:”center”})
$(“tr”).append(“<input type=’button’ class=’c2 c3′ name=’delete1′ value=’删除’/>”);
$(“tr”).append(“<input type=’button’ class=’c2 c3′ name=’addtop’ value=’添加上一行’/>”);
$(“tr”).append(“<input type=’button’ class=’c2 c3′ name=’addbottom’ value=’添加下一行’/>”);
$(“.c3″).css({width:”150px”,height:”42px”,background:”#e35435″,border:”1px solid black”})
$(“input[name=’addtop’]”).click(function(){
var newtr=$(this).parent().clone(true);
newtr.children(“td”).html(“”);
$(this).parent().before(newtr);
newtr.css(“background”,”red”);
})
$(“input[name=’addbottom’]”).click(function(){
var newtr=$(this).parent().clone(true);
$(this).parent().after(newtr);
newtr.children(“td”).html(“”);
newtr.css(“background”,”gold”);
})
$(“input[name=’delete1′]”).click(function(){
$(this).parent().detach();
})
$(“td”).click(function(e){
var that=this;
var content=$(that).text();
$(that).html(“<input type=’text’ class=’in1′ />”);
$(“input[class=’in1′]”).css({width:”150px”,height:”38px”,border:”0″,textAlign:”center”})
$(“input[class=’in1′]”).focus();
$(“input[class=’in1′]”).val(content);
$(“input[class=’in1′]”).click(function(e){
e.stopPropagation();
})
$(“input[class=’in1′]”).blur(function(){
var content=$(this).val();
$(that).text(content);
})
})
})
</script>
</body>
</html>