编程语言
首页 > 编程语言> > JavaScript实现全选反选的小案例

JavaScript实现全选反选的小案例

作者:互联网

<div class="wrap">
        <table>
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="j_cbAll">
                    </th>
                    <th>商品</th>
                    <th>价格</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="checkbox"></td>
                    <td>手机</td>
                    <td>5999</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td>电脑</td>
                    <td>4000</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td>电视</td>
                    <td>5290</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td>相机</td>
                    <td>1290</td>
                </tr>
            </tbody>
        </table>
    </div>
<style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .wrap {
            width: 300px;
            margin: 100px auto 0;
        }
        
        table {
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;
            width: 300px;
        }
        
        th,
        td {
            border: 1px solid #d0d0d0;
            color: #404040;
            padding: 10px;
        }
        
        th {
            background-color: #e99;
            font: bold 16px '微软雅黑';
            color: #fff;
        }
        
        td {
            font: 14px '微软雅黑';
        }
        
        tbody tr {
            background-color: #f0f0f0;
        }
        
        tbody tr:hover {
            cursor: pointer;
            background-color: #fafafa;
        }
    </style>
<script>
        var j_cbAll = document.querySelector('#j_cbAll');
        var j_tbs = document.querySelector('tbody').querySelectorAll('input')
            //console.log(j_tbs)
        j_cbAll.onclick = function() {
            //console.log(this.checked)
            for (var i = 0; i < j_tbs.length; i++) {
                j_tbs[i].checked = this.checked;
            }
        }
        for (var i = 0; i < j_tbs.length; i++) {
            j_tbs[i].onclick = function() {
                var flag = true;
                for (var i = 0; i < j_tbs.length; i++) {
                    if (!j_tbs[i].checked) {
                        flag = false;
                        break;
                    }
                }
                j_cbAll.checked = flag;
            }
        }
    </script>

标签:checked,color,tbs,JavaScript,反选,cbAll,全选,var,border
来源: https://blog.csdn.net/weixin_45074231/article/details/121318648