js实现全选、全不选、反选

时间:2022-03-29 09:06:50

一个js的简单实验

思路:通过 document.getElementsByTagName('input')获取集合,判断类型是否为checkbox,再对其进行操作

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form>
        <input type="checkbox" name="fruit" value="苹果">苹果
        <input type="checkbox" name="fruit" value="香蕉">香蕉
        <input type="checkbox" name="fruit" value="芒果">芒果
        <input type="checkbox" name="fruit" value="葡萄">葡萄
    </form>
    <button id="all">全选</button>
    <button id="not">全不选</button>
    <button id="reve">反选</button>

    <script>
        var all = document.getElementById('all');
        var not = document.getElementById('not');
        var reve = document.getElementById('reve');
        var fruit = document.getElementsByTagName('input');
        //全选
        all.onclick = function(){
            for(var i=0;i<=fruit.length;i++){
                if(fruit[i].type == 'checkbox'){
                    fruit[i].checked = true;
                }
            }
        };
        //全不选
        not.onclick = function(){
            for(var i=0;i<=fruit.length;i++){
                if(fruit[i].type == 'checkbox'){
                    fruit[i].checked = false;
                }
            }
        };
        //反选
        reve.onclick = function(){
            for(var i=0;i<=fruit.length;i++){
                if(fruit[i].type == 'checkbox'){
                    /*if(fruit[i].checked == true){
                        fruit[i].checked = false;
                    }else{
                        fruit[i].checked = true;
                    }*/
                    fruit[i].checked = !fruit[i].checked;
                }
            }
        };
    </script>
</body>
</html>

 js实现全选、全不选、反选