第一篇博客,开启技术博客的生涯,欢迎大家批评指教(坚信妹子也可以做好程序猿)
今天想说帮公司做项目的时候遇到的一个小问题,动态添加html
元素以后再去事件监听出问题。在实际开发中会遇到要给动态生成的html
元素绑定触发事件的情况。
就是上面的一张表格要动态实现添加行,然后序列号还要随着增加,当删除的时候序列号依旧是按顺序排列。
刚开始使用jQuery
的on
方法来解决,但是发现一个问题会出现事件绑定很多次的问题。然后查询了网上的一些资料,使用live进行事件委托,然而还是出现事件绑定多次bug,很崩溃。最后试着用onclick
内联,可以完美解决,这里其实有点困惑,但是算是比较完美的解决这个问题。
html:
<div class="col-sm-12">
<div class="panel panel-primary">
<div class="panel-body">
<div class="block-content collapse in">
<div class="span12">
<table id="volTab" class="table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>证件号码</th>
<th>手机号码</th>
<th>银行卡号</th>
<th>E-mail</th>
<th>地址</th>
<th>删除</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td>1</td>
<td><div><input type="text" class="form-control"/></div></td>
<td><div><input type="text" class="form-control"/></div></td>
<td><div><input type="text" class="form-control"/></div></td>
<td><div><input type="text" class="form-control"/></div></td>
<td><div><input type="text" class="form-control"/></div></td>
<td><div><input type="text" class="form-control"/></div></td>
<td><i class="fa fa-fw fa-minus"></i></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<button type="button" id="add" style="width:100px;float:left;margin:0 auto;margin-left:40%" class="btn btn-block btn-primary">添加</button>
<button type="button" id="submit" style="width:100px;float:left;margin:0 auto;margin-left:5px" class="btn btn-block btn-default">提交</button>
js:
<script>
$("#add").click(function(){
var len=$("#volTab tr").length;
$("#volTab").append("<tr id="+len+">"
+"<td>"+len+"</td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><i class='fa fa-fw fa-minus' onclick=\'deltr("+len+")\'"+"'></i></td>"+"</tr>");
});
var deltr =function(index)
{
debugger;
var b=$("#volTab tr").length;
$("#"+index).remove();
for(var i=index+1,j=index;i<=b;i++,j++){
$("#"+i).replaceWith("<tr id="+(i-1)+">"
+"<td>"+(i-1)+"</td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><input type='text' class='form-control'></td>"
+"<td><i class='fa fa-fw fa-minus' onclick=\'deltr("+(i-1)+")\'"+"'></i></td>"+"</tr>");
}
}
</script>