孙肖宁

jQuery实现表格的全选和反选
描述:当点击全选是,选中下面全部的复选框,当复选框全部选中时,点击返现则取消选择,当复选框有没有选中的项的时候,全...
扫描右侧二维码阅读全文
12
2018/05

jQuery实现表格的全选和反选

描述:当点击全选是,选中下面全部的复选框,当复选框全部选中时,点击返现则取消选择,当复选框有没有选中的项的时候,全选按钮取消全选。使用的jquery的版本是1.8.
示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全选和反选 </title>
    <style>
        table {
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;
            width: 300px;
        }
        th,
        td {
            border: 1px solid #d0d0d0;
            color: #404060;
            padding: 10px;
        }

        th {
            background-color: #09c;
            font: bold 16px "微软雅黑";
            color: #fff;
        }

        td {
            font: 14px "微软雅黑";
        }

        tbody tr {
            background-color: #f0f0f0;
        }

        tbody tr:hover {
            cursor: pointer;
            background-color: #fafafa;
        }
    </style>
    <script src="jquery.min.js"></script>
    <script>
        $(function () {
            $("#theadInp").click(function () {
                $("#tbody input:checkbox").prop("checked",$(this).prop("checked"));
            });
            $("#tbody input:checkbox").click(function () {
                if($("#tbody input:checkbox").length === $("#tbody input:checked").length){
                    $("#theadInp").prop("checked",true);
                }else {
                    $("#theadInp").prop("checked",false);
                }
            })
        });
    </script>
</head>
<body>
<div>
    <table>
        <thead>
        <tr>
            <th><input type="checkbox" id="theadInp"></th>
            <td>标题</td>
        </tr>
        </thead>
        <tbody id="tbody">
        <tr>
            <td><input type="checkbox"></td>
            <td>1</td>
        </tr>
        <td><input type="checkbox"></td>
        <td>1</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>1</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>1</td>
        </tr>
        </tbody>
    </table>
</div>
</body>
</html>
Last modification:May 12th, 2018 at 07:59 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment