JavaScript实现全选或反选功能
作者:小方同学-方鹏远
这篇文章主要为大家详细介绍了JavaScript实现全选或反选功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了JavaScript实现全选或反选功能的具体代码,供大家参考,具体内容如下
代码如下
<!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>
运行结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。