JavaScript实现复选框的全选、不选、反选

方法一:

<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script type="text/javascript" src="01.js"></script>
</head>
<body>
<input type="button" id="All" value="全选" /><br />
<input type="button" id="uncheck" value="不选" /><br />
<input type="button" id="othercheck" value="反选" /><br />
<div id="div">
<input type="checkbox" /><br />
<input type="checkbox" /><br />
<input type="checkbox" /><br />
</div>
<script type="text/javascript" src="Untitled-12.js"></script>
</body>
</html>
     var CheckAll=document.getElementById('All');
     var UnCheck=document.getElementById('uncheck');
     var OtherCheck=document.getElementById('othercheck');
     var div=document.getElementById('div');
     var CheckBox=div.getElementsByTagName('input');
     CheckAll.onclick=function()
     {
            for(i=0;i<CheckBox.length;i++){
                    CheckBox[i].checked=true;
                }
     }
     UnCheck.onclick=function()
     {
            for(i=0;i<CheckBox.length;i++){
                   CheckBox[i].checked=false;
                 }
     }
     othercheck.onclick=function()
     {
            for(i=0;i<CheckBox.length;i++)
     {
                    if(CheckBox[i].checked==true)  /*注意这里是双等于号;一个等于号是赋值的意思,双等于号是判断的意思*/
{ CheckBox[i].checked
=false; } else{ CheckBox[i].checked=true } } }

方法二:

<html>
    <head><meta charset="UTF-8">
     <script type="text/javascript" defer="defer" src="01.js"></script>
    </head>
    <body>
        <div id="div">
            <input type="checkbox" /><br />
            <input type="checkbox" /><br />
            <input type="checkbox" /><br />
            <input type="checkbox" /><br />
            <input type="checkbox" /><br />
            <input type="checkbox" /><br />
            <input type="checkbox" /><br />
            <input type="checkbox" /><br />
        </div>
        <input type="button" value="全选" onclick="CheckAll()"/><br />
        <input type="button" value="不选" onclick="UnCheck()"/><br />
        <input type="button" value="反选" onclick="othercheck()"/><br />
    </body>
</html>
            var CheckBox=div.getElementsByTagName('input');
             
            //全选
            function CheckAll(){
                for(i=0;i<CheckBox.length;i++){CheckBox[i].checked=true;};
            };
             
            //不选
            function UnCheck(){
                for(i=0;i<CheckBox.length;i++){CheckBox[i].checked=false;};
                };
             
            //反选
            function othercheck(){
                for(i=0;i<CheckBox.length;i++){
                    if(CheckBox[i].checked==true)    /*注意这里是双等于号;一个等于号是赋值的意思,双等于号是判断的意思*/
                    { 
CheckBox[i].checked=false;
}
else{ CheckBox[i].checked=true} } };
原文地址:https://www.cnblogs.com/xinlvtian/p/7862212.html