【前言】
刚刚给后台加了个全选后快捷删除功能,这里用我用jquery来实现。
(1)全选和全部选
(2)获取选择的数据
【主体】
用jquery处理的话,最好不要用attr方法增加属性,否则会出现第三次点击不生效的情况,用prop方法较好。用prop方法时注意jquery版本,必须是1.8之后的版本,否则不支持
<table class="table table-bordered "> <thead class="tab_head"> <tr> <td> <input type="checkBox" onclick="selectAll()"></td> <th>名称</th> <th>角明</th> <th>所统</th> </tr> </thead> <tbody> <tr> <td> <input type="checkBox"></td> <td>系管</td> <td>管角</td> <td>安台</td> </tr> <tr> <td> <input type="checkBox"></td> <td>统管</td> <td>员角</td> <td>安平</td> </tr> <tr> <td> <input type="checkBox"></td> <td>管理</td> <td>角色</td> <td>武进</td> </tr> </tbody> </table> <script> function selectAll(){ $("input[type='checkBox']").each( function() { if($(this).prop("checked")==true) { $("input[type='checkBox']").prop('checked',true); return; } else { $("input[type='checkBox']").prop('checked',false); return; } }); } </script>
以上便可以完成全选和全不选
$('#batchDel').on('click',function(){ var idList = ''; $.each($('input:checkBox:checked'),function(){ idList+=$(this).val()+','; }); //这里输出结果格式会是 on,aaa,bbb,ccc, 所以接下来要截取掉前后多余字符on,和, var idListone = idList.substr(0,idList.length - 1);//删除末尾, var idListtwo = idListone.replace("on,","");//删除首位的on,console.log(idListtwo) if(idListtwo == 'on'){ layer.alert('请选择要删除的文章'); }else if(idListtwo == ''){ layer.alert('请选择要删除的文章'); }else{ if(confirm('确认删除')){ window.location.href = "__MODULE__/Article/del/id/"+idListtwo; } } })
补充说明:弹框用的layer进行渲染
【拓展】JS如何去除指定字符串
两种方式可以实现,这里推荐使用第一种方法
1:使用replace函数替换
var str="hello world!";
str=str.replace("l","");
2:使用字符串分割函数在聚合
var str="hello world!"
var items=str.split("o")
会得到一个数组,数组中包括利用o分割后的多个字符串(不包括o)
var newStr=items.join("");
会得到一个新字符串,将数组中的数组使用空串连接成一个新字符串
.