webAPI

表格中的全选、全不选、反勾

2019-05-07  本文已影响0人  椋椋夜色

<!DOCTYPE html>
<html lang="zh-CN">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> 表格中的全选、全不选、反勾 </title>

<style>
    table {
        margin: 100px auto;

        /* 合并单元格边框,给table加的 */
        border-collapse: collapse;
    }

    th {
        background-color: #0099cc;
        color: white;
    }

    td {
        width: 120px;
        height: 35px;
        text-align: center;
        line-height: 35px;
    }

    th,
    td {

        border: 1px solid #000;
    }
</style>

</head>

<body>

<table>
    <thead>
        <tr>
            <th><input type="checkbox" id="all">全选/全不选</th>
            <th>菜名</th>
            <th>商家</th>
            <th>价格</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" class="food"></td>
            <td>红烧肉</td>
            <td>隆江猪脚饭</td>
            <td>200</td>
        </tr>
        <tr>
            <td><input type="checkbox" class="food"></td>
            <td>香酥排骨</td>
            <td>隆江猪脚饭</td>
            <td>300</td>
        </tr>
        <tr>
            <td><input type="checkbox" class="food"></td>
            <td>北京烤鸭</td>
            <td>隆江猪脚饭</td>
            <td>10</td>
        </tr>
    </tbody>

    <script>
        // 找到全选/全不选
        var all = document.getElementById('all');

        // 找tbody里的checkbox
        var food = document.getElementsByClassName('food');

        // 给全选/全不选加点击事件
        all.onclick = function () {
            //遍历所有的food
            for (var i = 0; i < food.length; i++) {
                food[i].checked = this.checked;
            }
        }
        // 遍历所有的food,给它们加点击事件 
        for (var i = 0; i < food.length; i++) {
            food[i].onclick = function () {
                var add = 0;
                for (var j = 0; j < food.length; j++) {
                    if (food[j].checked) {
                        add++;
                    }
                } // 其实它要的值就是 这个判断的结果,所以直接把结果赋值就行了
                all.checked = add == food.length;
            }
        }
    </script>

</body>

</html>

上一篇下一篇

猜你喜欢

热点阅读