美文网首页
全选与反选

全选与反选

作者: 沫忘丶 | 来源:发表于2019-04-12 09:18 被阅读0次
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            ul{
                list-style: none;
                padding: 0;
                margin: 0;
            }
        </style>
    </head>
    <body>
        <ul id="list">
            <li><input type="checkbox" name="basketball">篮球</li>
            <li><input type="checkbox" name="basketball">足球</li>
            <li><input type="checkbox" name="basketball">排球</li>
            <li><input type="checkbox" name="basketball">网球</li>    
        </ul>
        <input id="all" type="checkbox" name="all">全选
        <br>
        <button type="button">反选</button>
        
        <script type="text/javascript">
            var oList = document.getElementById('list');
            var aInp = oList.getElementsByTagName('input');
            var oBtn = document.getElementsByTagName('button')[0];
            var oAll = document.getElementById("all");
            var onOff = true;
            oAll.onclick = function() {
                if(onOff){
                    for (var i = 0; i < aInp.length; i++) {
                        aInp[i].checked = true;
                }   
            }
            else{
                for (var i = 0; i < aInp.length; i++) {
                        aInp[i].checked = false;
                }   
            }
            onOff = !onOff;
        }
        for(var i = 0;i<aInp.length;i++){
            aInp[i].onclick = function(){
                for(var j = 0;j<aInp.length;j++){
                    if(!aInp[j].checked){
                        oAll.checked = false;
                        onOff = true;
                        return;
                    }
                }
                oAll.checked = true;
                onOff = false;
            }
        }
            oBtn.onclick = function(){
                for(var i = 0;i<aInp.length;i++){
                    aInp[i].checked = !aInp[i].checked;
                }
            }
        </script>
    </body>
</html>

相关文章

网友评论

      本文标题:全选与反选

      本文链接:https://www.haomeiwen.com/subject/uurqwqtx.html