jQuery和js实现全选框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../../jquery-3.4.1.min.js"></script>
</head>
<body>
<table border="1px" cellpadding="20px" width="500px">
    <thead>
    <tr>
        <td><input type="checkbox"></td>
        <td>姓名</td>
        <td>年龄</td>
        <td>武器</td>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td><input type="checkbox"></td>
        <td>刘备</td>
        <td>40</td>
        <td>雌雄双剑</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>关羽</td>
        <td>35</td>
        <td>青龙偃月刀</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>张飞</td>
        <td>34</td>
        <td>丈八蛇矛</td>
    </tr>
    </tbody>
</table>
<!----------------------------------jQuery实现----------------------------------->
<script>
    $('thead input').change(function () {
        let isChecked = $(this).prop('checked');

        $('tbody input').prop('checked', isChecked);
    });

    $('tbody input').click(function () {
        let allCount=$('tbody input').length;
        let checkCount = $('tbody input:checked').length;
        let isAllChecked = checkCount === allCount;
        $('thead input').prop('checked',isAllChecked);
    })
</script>
<!----------------------------------JS实现------------------------------------------->
<script>
    let boxThead = document.querySelector("thead").querySelector('input');
    let boxTbody = document.querySelector("tbody").querySelectorAll('input');
    boxThead.onchange = function () {
        let is = boxThead.checked;
        for (let i = 0; i < boxTbody.length; i++) {
            boxTbody[i].checked = is;
        }
    };

    let oo = boxTbody[0].onchange = function () {
        if (boxTbody[0].checked === true) {
            return 'one-true';
        }
    };
    let tt = boxTbody[1].onchange = function () {
        if (boxTbody[1].checked === true) {
            return 'two-true';
        }
    };
    let th = boxTbody[2].onchange = function () {
        if (boxTbody[2].checked === true) {
            return 'three-true';
        }
    };

    for (let i = 0; i < boxTbody.length; i++) {
        boxTbody[i].onchange = function () {
            if (oo() === "one-true" && tt() === "two-true" && th() === "three-true") {
                boxThead.checked = true;
            }else {
                boxThead.checked = false;
            }
        }
    }
</script>
</body>
</html>

image.png

image.png
image.png

发布了13 篇原创文章 · 获赞 4 · 访问量 349

猜你喜欢

转载自blog.csdn.net/printf_hello/article/details/103927209