日期:2014-05-16  浏览次数:20336 次

JavaScript中复选框的全选和反选功能的实现
这是我平时学习时的练习,贴出来跟大家一起讨论,本来是新手,欢迎老手指正错误。 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">  
<html>  
    <head>  
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
        <title>Test CheckBox</title>  
        <style type="text/css">  
            body{   
                font-family:Courier;   
            }   
        </style>  
        <script type="text/javascript">  
            function checkAll(){   
                var checkAll = document.getElementById('chkAll') ;   
                var checkBox = document.getElementById('checkBox') ;   
                var arr = new Array() ;   
                arr = checkBox.getElementsByTagName('input') ;   
                if(checkAll.checked==true){  //checkAll selected   
                    for(i=0; i<arr.length; i++){   
                        arr[i].checked = true ;    
                    }   
                }   
                if(checkAll.checked==false){   
                    for(i=0; i<arr.length; i++){   
                        arr[i].checked = false ;       
                    }   
                }   
  
            }   
            function checkCancel(){   
                var checkCancel = document.getElementById('chkCancel') ;   
                var checkBox = document.getElementById('checkBox') ;   
                var arr = new Array() ;   
                arr = checkBox.getElementsByTagName('input') ;   
                if(checkCancel.checked==true){ //checkCancel selected   
                    for(i=0; i<arr.length; i++){   
                        if(arr[i].checked == true){   
                            arr[i].checked = false ;   
                        }else {   
                            arr[i].checked = true ;   
                        }      
                    }   
                }   
            }   
        </script>  
    </head>  
    <body>  
           
        <input type="checkbox" id="chkAll" onclick="checkAll()"/> check All <br/>  
        <input type="checkbox" id="chkCancel" onclick="checkCancel()"/> check Cancel <br/>  
            <br />       
        <div id="checkBox">  
        <input type="checkbox" id="chk1"/> 1 <br/>  
        <input type="checkbox" id="chk2"/> 2 <br/>  
        <input type="checkbox" id="chk3"/> 3 <br/>  
        <input type="checkbox" id="chk4"/> 4 <br/>  
        <input type="checkbox" id="chk5"/> 5 <br/>  
        </div>  
    </body>  
</html>  



下图是显示效果