<html> <head> <title>全选和取消全选</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script language="javascript"> function checkAllorcancelAll(){ //思路:1.获取checkbox的选中状态;1.1获取checkbox元素 var chkElt = document.getElementById("chkElt"); //1.2获取选中状态 var checked = chkElt.checked; //2.若checked=true,选中所有复选框; //2.1获取所有复选框 var allInterests = document.getElementsByName("interest"); //2.2遍历取出每个复选框对象 var mySpan = document.getElementById("mySpan"); if(checked){ //全选,设置复选框的选中状态 for(var i=0;i<allInterests.length;i++){ allInterests[i].checked = true; } mySpan.innerHTML="取消全选"; }else{ //取消全选 checked=false; for(var i=0;i<allInterests.length;i++){ allInterests[i].checked = false; } mySpan.innerHTML="全选"; } } </script> </head> <body> <input type = "checkbox" id="chkElt" onclick="checkAllorcancelAll()"> <span id="mySpan">全选</span><br> 运动<input type = "checkbox" name="interest" value="sport" /><br> 音乐<input type = "checkbox" name="interest" value="music" /><br> 美食<input type = "checkbox" name="interest" value="food" /><br> 睡觉<input type = "checkbox" name="interest" value="sleep" /><br> 跳舞<input type = "checkbox" name="interest" value="dance" /><br> </body> </html> </html>
原文:http://www.cnblogs.com/wangqiang4518/p/5730998.html