Java教程

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>

这篇关于JavaScript实现全选反选的小案例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!