Jquery4_控制Dom元素_checkbox全選及反選

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        // 封裝方法 判斷選中狀態
        function checkcheck() {
            // 假設所有的checkbox都選中了
            var isCheckAll = true;

            $(":checkbox[id*=child]").each(function () {
                if (!$(this).attr("checked")) {
                    isCheckAll = false;
                }
            });

            return isCheckAll;
        };

        $(function () {
            // 全選
            $("#quanxuan").click(function () {
                // 讓子的和父的選中狀態一致  (由於Jquery沒有封裝checkbox的check屬性所以要用attr())
                $(":checkbox[id*=child]").attr("checked", $(this).attr("checked"));
            });


            // 給子的checkBox註冊事件
            $(":checkbox[id*=child]").click(function () {
                $("#quanxuan").attr("checked", checkcheck());
            });

            // 反選
            $("#fanxuan").click(function () {
                $(":checkbox[id*=child]").each(function () {
                    $(this).attr("checked", !$(this).attr("checked"));
                    $("#quanxuan").attr("checked", checkcheck());
                });
            });

        });
    </script>
</head>
<body>
   <input type="checkbox" id="quanxuan" />全選
   <input type="checkbox" id="fanxuan" />反選
   <br />
   <input type="checkbox" id="child1" value="chifan" />吃飯
   <input type="checkbox" id="child2" value="shuijiao" />睡覺
   <input type="checkbox" id="child3" value="dadoudou" />打豆豆
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章