批量删除之-复选框

在进行的项目中需用到批量删除,删除则需用到复选框,现贴出代码以备后用。

html代码如下

<button class="btn btn-xs btn-danger" onclick="delBatchInfo('patrolTask')"><i class="ace-icon fa fa-trash-o bigger-120"></i>删除勾选</button>
<table id="datatable" class="table table-striped table-bordered table-hover">
    <thead><tr><th class="center"><label><input type="checkbox" class="ace"  name="delBatch"/><span class="lbl"></span></label></th><th class="center">编号</th></tr> </thead>
    <tbody><tr><th class="center"><label><input type="checkbox" class="ace"  name="delBatch"  name="delBatch" value="'+data.data[item].id+'"/><span class="lbl"></span></label></th><td class="center"></td></tr></tbody>
</table>

js

$('table th input:checkbox').on('click' , function(){
    var that = this;
    $(this).closest('table').find('tr > td:first-child input:checkbox')
    .each(function(){
        this.checked = that.checked;
        $(this).closest('tr').toggleClass('selected');
});
delBatchInfo方法
/**********************************************
函数名:delBatchInfo
功能:批量删除记录
作者:milan
************************************************/
function delBatchInfo(type){
    var DelMessHtml="";
    var checkedNum=$("input[name='delBatch']:checked").length;
        if(checkedNum == 0) { 
            alert("请选择删除对象!"); 
            return; 
        } 
        
    if(confirm("警告:您要彻底删除记录吗?")){var checkedList=new Array();
        $("#datatable").find('tr > td:first-child input:checkbox')
        .each(function(){
            checkedList.push($(this).val());
        });                
        
    }
    
    ...
        
    
}

当我在删除提示中传递值时,删除出错,错误代码如下:

if(confirm("警告:您要彻底删除记录吗?")){
    var checkedList=new Array();
    $("input[name='delBatch']:checked").each(function(){
        checkedList.push($(this).val());
    });
}

原因是

$("input[name='delBatch']:checked").each(function(){
这代码把全部复选框都遍历,包括总勾选的复选框。总复选框是没有ID值的。
正确代码应:
$("#datatable").find('tr > td:first-child input:checkbox')

这样才是只选择tr中td的复选框


每次删除后,执行setListTable(nowpage)刷新页面后,总复选框还是处理勾选状态,如图:


只能把table>thead的内容也放到
setListTable方法里面才能解决
var tableHmtl='<thead><tr><th class="center"><label><input type="checkbox" class="ace"   name="delBatch" id="checkAll"/><span class="lbl"></span></label></th><th class="center">编号</th></tr> </thead> <tbody>';
tableHmtl+='<tr><td class="center"><label><input type="checkbox" class="ace"  name="delBatch" value="'+data.data[item].id+'"/><span class="lbl"></span></label></td><td class="center">'+data.data[item].id+'</td><tr>';
tableHmtl+='</tbody>';                                                
$("#datatable").html(tableHmtl);
                                     



原文地址:https://www.cnblogs.com/mailan/p/4935344.html