JS控制 checkbox的全选与反选
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> *{margin:0px; padding:0px;} body{font:12px/1.5 宋体, Arial, Helvetica, sans-serif; color:#333;} input{vertical-align:middle; margin:0px 5px 3px 0px; *margin:0px 2px 3px 0px;} a{color:#39F; text-decoration:none;} a:hover{color:#F60;} table{border-collapse:collapse;} th,td{border:1px solid #EFEFEF; padding:8px 4px;} th{font-weight:normal; text-align:left;} </style> <script> function checkList(obj){ var oBox = typeof obj == "string" ? document.getElementById(obj) : obj; var aInput = oBox.getElementsByTagName("input"); var aCheck = []; var i = checkedNum = 0; for(i=0;i<aInput.length;i++){ if(aInput[i].getAttribute("type") == "checkbox"){ aCheck.push(aInput[i]); } } /*因为aInput为oBox中的所有input,万一表单中有其他type的input的话从aInput中获取type为checkbox的元素,不知js有没有比较方便的办法获取checkbox,求指教*/ var oAll = getByClass(oBox,"all")[0]; var oReverse = getByClass(oBox,"reverse")[0]; for(i=0;i<aCheck.length;i++){ aCheck[i].onclick = function(){ if(this == oAll){ for(i=0;i<aCheck.length;i++){ aCheck[i].checked = this.checked; } } else{ if(!this.checked){ oAll.checked = false; } checkAll(); } } } oReverse.onclick = function(){ for(i=0;i<aCheck.length;i++){ if(aCheck[i] != oAll){ aCheck[i].checked = !aCheck[i].checked; } } checkAll(); } function getByClass(oParent,tClass){ var tempObj = oParent.getElementsByTagName("*"); var targObj = []; var filter = new RegExp("\\b" + tClass + "\\b"); for(var i=0;i<tempObj.length;i++){ if(filter.test(tempObj[i].className)){ targObj.push(tempObj[i]); } } return targObj; } function checkAll(){ for(i=0;i<aCheck.length;i++){ if(aCheck[i].checked){ checkedNum++; } } checkedNum == aCheck.length - 1 ? oAll.checked = true : oAll.checked = false; checkedNum = 0; } } </script> </head> <body> <table cellpadding="0" cellspacing="0" border="0" width="100%" id="list"> <tr> <th width="20%"><input class="all" type="checkbox"/>全选(<a class="reverse" href="javascript:void(0)">反选</a>)</th> <th>item</th> </tr> <tr> <td><input type="checkbox"/></td> <td>item1</td> </tr> <tr> <td><input type="checkbox"/></td> <td>item2</td> </tr> <tr> <td><input type="checkbox"/></td> <td>item3</td> </tr> <tr> <td><input type="checkbox"/></td> <td>item4</td> </tr> <tr> <td><input type="checkbox"/></td> <td>item5</td> </tr> </table> <script> checkList("list"); </script> </body> </html>