js全选或反选功能
小方同学-方鹏远 人气:0想了解JavaScript实现全选或反选功能的相关内容吗,小方同学-方鹏远在本文为您仔细讲解js全选或反选功能的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js,全选,反选,下面大家一起来学习吧。
代码如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>案例--表格全选</title> <style> table { border: 1px solid; margin: auto; width: 500px; } td, th { text-align: center; border: 1px solid; } .out { background-color: white; } .over { background-color: pink; } div{ margin-top: 10px; text-align: center; } </style> <script> window.onload = function () { //全选 document.getElementById("checkAll").onclick = function () { var cbs = document.getElementsByName("cb"); for (var i = 0; i < cbs.length; i++) { cbs[i].checked = true; } } //全不选 document.getElementById("unCheckAll").onclick = function () { var cbs = document.getElementsByName("cb"); for (var i = 0; i < cbs.length; i++) { cbs[i].checked = false; } } //反选 document.getElementById("reCheck").onclick = function () { var cbs = document.getElementsByName("cb"); for (var i = 0; i < cbs.length; i++) { cbs[i].checked = !cbs[i].checked; } } //鼠标经过,颜色变化 var trs = document.getElementsByTagName("tr"); for (var i = 0; i < trs.length; i++) { trs[i].onmouseover = function () { this.className = "over"; } trs[i].onmouseout = function () { this.className = "out"; } } //选中顶部复选框,全选 document.getElementById("firstCb").onclick = function () { var cbs = document.getElementsByName("cb"); for (var i = 0; i < cbs.length; i++) { cbs[i].checked = this.checked; } } } </script> </head> <body> <table> <caption>学生信息表</caption> <tr> <td><input type="checkbox" name="cb" id="firstCb"></td> <td>编号</td> <td>姓名</td> <td>性别</td> <td>操作</td> </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" value="全选" id="checkAll"> <input type="button" value="全不选" id="unCheckAll"> <input type="button" value="反选" id="reCheck"> </div> </body> </html>
运行结果
加载全部内容