js实现全选、全不选、反选的功能
<!DOCTYPE html> <html> <head> <META charset="utf-8"/> <link rel="stylesheet" href="table.css"/> <style> </style> </head> <body> 爱好:<br/> 读书:<input type="checkbox" name="hobby" value="0"/><br/> 游泳:<input type="checkbox" name="hobby" value="1"/><br/> 听歌:<input type="checkbox" name="hobby" value="2"/><br/> <hr/> <button value="1" onclick="setAll()">全选</button> <button value="0" onclick="setNo()">全不选</button> <button value="-1" onclick="setOthers()" >反选</button> </body> <script src="util.js"></script> <script> /* //全选函数 function setAll() { var hobbies = document.getElementsByName("hobby"); for (var i = 0; i < hobbies.length; i++) { hobbies[i].checked = true; } } //全不选函数 function setNo() { var hobbies = document.getElementsByName("hobby"); for (var i = 0; i < hobbies.length; i++) { hobbies[i].checked = false; } } //反选 function setOthers() { var hobbies = document.getElementsByName("hobby"); for (var i = 0; i < hobbies.length; i++) { if (hobbies[i].checked == false) hobbies[i].checked = true; else hobbies[i].checked = false; } } */ var inputs=$('input[name=hobby]'); var btns=$('button'); for(var i=0;i<btns.length;i++){ btns[i].onclick=function(){ var value=this.getAttribute('value'); for(var i=0;i<inputs.length;i++){ if(value==1){ inputs[i].checked=true; }else if(value==0){ inputs[i].checked=false; }else{ inputs[i].checked=false; } } } } </script> </html>
util.js
function $(n){ if(/^<([a-zA-Z]+)>$/.test(n)){ var tagName = RegExp.$1; return document.createElement(tagName); }else{ return document.querySelectorAll(n); } }