有下面这个例子:
上面的表格中页面刚打开的时候如上图所示,最右边的“-”表示删除当前行的数据,如果我们使用
$("span").bind("click",function(){
$(this).parents("tr").remove();
})
或者
$("span").click(function(){
$(this).parents("tr").remove();
})
来处理删除操作(其中span为“-”的选择器),就会有如下的问题:
页面初始展示的3行是可以删除的,但是后来通过新增按钮新增的行是不能删除的,这是因为bind或者click(fn)的方式是不能处理动态创建元素的事件绑定的,通过我之前讲的jquery中的事件处理函数,此时可以使用delegate、on或者live(需要jquery1.8以下才有live函数)来处理。
如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户管理</title>
<link type="text/css" rel="stylesheet" href="normalize.css" />
<link type="text/css" rel="stylesheet" href="gridshow.css" />
<style>
#datatable td span{
margin:0 auto;
display:block;
width:20px;
height:20px;
background:url("icons.png") no-repeat -46px 0px;
cursor:pointer;
}
.addBtn{
background:#eef3fa url("add.png") no-repeat;
font-size:13px;
font-family:"微软雅黑";
color:blue;
border-radius:3px;
padding-left:20px;
cursor:pointer;
}
.toInsertTrDiv{
display:none;
}
</style>
</head>
<body>
<table class="datatable-head">
<thead>
<tr>
<td>日期</td>
<td>时间</td>
<td>银行名称</td>
<td>账号</td>
<td>出入账名称</td>
<td >金额</td>
<td>对方国别</td>
<td >交易性质名称</td>
<td >操作</td>
</tr>
</thead>
</table>
<div id="marquees">
<table id="datatable" class="datatable">
<tr>
<td >2016-6-1</td>
<td >09:30:08</td>
<td >上海浦东发展银行上海分行</td>
<td >FTN9884554100002014</td>
<td >入账</td>
<td class="xl69" style="border-top:none;border-left:none">2,199,975.00</td>
<td >香港</td>
<td >一般贸易</td>
<td><!--不使用live
<span onclick="del(this)"></span>
--> <span></span></td>
</tr>
<tr>
<td >2016-6-1</td>
<td >09:30:08</td>
<td >上海浦东发展银行上海分行</td>
<td >FTN9884554100002001</td>
<td >出账</td>
<td >14,447,235.82</td>
<td >中国</td>
<td >货物</td>
<td><!--不使用live
<span onclick="del(this)"></span>
--> <span></span></td>
</tr>
<tr>
<td>2016-6-1</td>
<td >09:30:08</td>
<td >上海浦东发展银行上海分行</td>
<td >FTN9884554100002001</td>
<td >入账</td>
<td >14,447,235.82</td>
<td >香港</td>
<td >一般贸易</td>
<td><!--不使用live
<span onclick="del(this)"></span>
--> <span></span></td>
</tr>
</table>
<div id="toInsertTrDiv">
<table>
<tr>
<td></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td>
<!--不使用live
<span onclick="del(this)"></span>
-->
<span></span>
</td>
</tr>
</table>
</div>
<input type="button" value="新增" class="addBtn">
</div>
</body>
</html>
javascript代码:
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script>
$("input[type='button']").bind("click",function(){
//还有个tbody
//var toInsertTr=$("#toInsertTrDiv table ").html();
//toInsertTr="<tr>"+toInsertTr+"</tr>"
var toInsertTr=$("#toInsertTrDiv table tr").html();
toInsertTr="<tr>"+toInsertTr+"</tr>"
$("#datatable").append(toInsertTr);//附加内容
});
function del(obj){
$(obj).parents("tr").remove();
}
//$("#datatable").on("click","span",function(){
//$("#datatable").delegate("span","click",function(){
$("span").live("click",function(){
//$("span").bind("click",function(){
$(this).parents("tr").remove();
})
</script>