JavaScript實現復選框全選功能

本文實例為大傢分享瞭JavaScript實現復選框全選的具體代碼,供大傢參考,具體內容如下

代碼:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            width: 300px;
            border-spacing: 0;
            /* text-align: center; */
            margin: 100px auto;
            border-collapse: collapse;
        }
        
        table tr:nth-child(n+2)>td {
            text-align: left;
            background-color: rgb(250, 245, 245);
            color: dimgray;
            font-size: 14px;
        }
        
        table tr:nth-child(1) {
            background-color: skyblue;
            color: white;
        }
        
        th,
        td {
            padding: 10px;
            border: 0.5px solid gray;
        }
    </style>
</head>

<body>
    <table>
        <tr>
            <th><input type="checkbox" name="" id="all"></th>
            <th>商品</th>
            <th>價格</th>
        </tr>
        <tr>
            <td><input type="checkbox" name="" id="ip8"></td>
            <td>iPhone8</td>
            <td>8000</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="" id="pro"></td>
            <td>iPad Pro</td>
            <td>5000</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="" id="air"></td>
            <td>iPad Air</td>
            <td>2000</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="" id="watch"></td>
            <td>Apple Watch</td>
            <td>2000</td>
        </tr>
    </table>

    <script>
        var all = document.getElementById('all');
        var items = document.querySelectorAll('tr>td>input');
        all.onclick = function() {
            for (var i = 0; i < items.length; i++) {
                items[i].checked = this.checked;
            }
        }


        for (var i = 0; i < items.length; i++) {
            items[i].onclick = function() {
                var flag_all = 1;
                for (var j = 0; j < items.length; j++) {
                    if (items[j].checked == 0) {
                        flag_all = 0;
                        all.checked = flag_all;
                        break;
                    }
                }
                all.checked = flag_all;
            }
        }
    </script>
</body>

</html>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀:

    None Found