jQuery实现全选和反选功能
- 核心代码
- attr() 与 prop() 区别
- 全部代码
核心代码
<script> $(function(){ var $selectAll = $("#selectAll"); var $unSelectAll = $("#unSelectAll"); var $selectRev = $("#selectRev"); //全选 $selectAll.click(function(){ let $checkbokes = $("table input[type='checkbox']"); $checkbokes.prop("checked",true); }) //全不选 $unSelectAll.click(function(){ let $checkbokes = $("table input[type='checkbox']"); $checkbokes.prop("checked",false); // $checkbokes.attr("checked",false); }) //反选 $selectRev.click(function(){ let checked = $("table input[type='checkbox']:checked"); let nochecked = $("table input[type='checkbox']:not(:checked)"); nochecked.prop("checked",true) checked.prop("checked",false); }) }) </script>
复制
attr() 与 prop() 区别
用attr()函数实现checked属性的设置在没有人为点击方框时是能用的,但是当某个复选框被选中时,无论全不选,反选对这个框都失效了.
勾选编号1复选框:
点击反选,控制台显示的是编号1和编号2的标签,可以看到没有checked属性,而编号2的有checked属性
再次点击反选,编号2的checked属性被清除了,而编号1没有反应,但是复选框还是勾选状态
attr函数操作的是人为添加的属性,不是原本标签包含的属性,而checked这种原生属性最好使用prop函数进行操作.
全部代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表格全选</title> <style> table { border: 1px solid; width: 500px; margin-left: 30%; } td, th { text-align: center; border: 1px solid; } div { margin-top: 10px; margin-left: 30%; } .out { background-color: white; } .over { background-color: pink; } </style> <script src="../js/jquery-3.4.1.min.js"></script> <script> $(function(){ var $selectAll = $("#selectAll"); var $unSelectAll = $("#unSelectAll"); var $selectRev = $("#selectRev"); $selectAll.click(function(){ let $checkbokes = $("table input[type='checkbox']"); $checkbokes.prop("checked",true); }) $unSelectAll.click(function(){ let $checkbokes = $("table input[type='checkbox']"); $checkbokes.prop("checked",false); // $checkbokes.attr("checked",false); }) $selectRev.click(function(){ let checked = $("table input[type='checkbox']:checked"); let nochecked = $("table input[type='checkbox']:not(:checked)"); nochecked.prop("checked",true) checked.prop("checked",false); }) }) </script> </head> <body> <table> <caption>学生信息表</caption> <tr> <th><input type="checkbox" name="cb" id="firstCb" class="aa"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>操作</th> </tr> <tr> <td><input type="checkbox" name="cb"></td> <td>1</td> <td>令狐冲</td> <td>男</td> <td><a href="javascript:void(0) " onclick="delTr(this);">删除</a></td> </tr> <tr> <td><input type="checkbox" name="cb"></td> <td>2</td> <td>任我行</td> <td>男</td> <td><a href="javascript:void(0) " onclick="delTr(this);">删除</a></td> </tr> <tr> <td><input type="checkbox" name="cb"></td> <td>3</td> <td>岳不群</td> <td>?</td> <td><a href="javascript:void(0) " onclick="delTr(this);">删除</a></td> </tr> </table> <div> <input type="button" id="selectAll" value="全选"> <input type="button" id="unSelectAll" value="全不选"> <input type="button" id="selectRev" value="反选"> </div> </body> </html>
复制