使用js实现全选 单选 全部选

来源:互联网 发布:数据库服务器 交换机 编辑:程序博客网 时间:2024/04/30 05:34
/ 思路:1、获取元素。2、用for循环历遍数组,把checkbox的checked设置为true即实现全选,
// 把checkbox的checked设置为false即实现不选。3、通过if判断,如果checked为true选中状态的,

// 就把checked设为false不选状态,如果checked为false不选状态的,就把checked设为true选中状态。

html
    全选:<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 />
        <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 />
        <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 />
        <input type="checkbox" /><br />
    </div>
    ---------js代码--------
    <script>
window.onload=function(){
    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                                                                                                           
                        }
                    
                };
        };
};
之前感觉很难学,后来思路清晰了感觉写起来也没那么难了。有不足之处大家指出来
0 0
原创粉丝点击