JQuery全选和反选练习

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="Scripts/jquery-1.4.2.js"></script>
    <script type="text/javascript">
        //这个例子只在1.42下有效 在1.7和1.9版本中无效
        //表单选择器
        //$(":input"):选择所有的input,包含<input>、<textarea>、<select>、<button>。而$("input")只获取<input>
        //$(":text"):选取所有的单行文本框,等价于$("input[type=text]")
        //$(":password"):选取所有的密码框。同理还有radio、checkbox、submit、image、reset、button、file、hidden
        $(function () {
            //=====================1================================
            //给全选按钮注册事件
            $("#chkAll").click(function () {
                $(":checkbox[id*=Child]").attr("checked", $(this).attr("checked"));
            });
 
            ////给所有的子checkbox注册事件
            //$(":checkbox[id*=Child]").click(function () {
            //    relateCheckAll();
            //});
 
            //给所有子的checkbox注册事件(另一种写法):只写方法名不写括号
            $(":checkbox[id*=Child]").click(relateCheckAll);
 
            //给反选按钮注册事件
            $(":checkbox[value=反选]").click(function () {
                $(":checkbox[id*=Child]").each(function () {
                    $(this).attr("checked", !$(this).attr("checked"));
                });
                relateCheckAll();
            });
            
 
 
        });
 
        function relateCheckAll() {
            //设定所有的子checkbox都选中了
            var ischeckAll = true;
            $(":checkbox[id*=Child]").each(function () {
                if (!$(this).attr("checked")) {
                    ischeckAll = false;
                    //跳出each循环用return false;
                    return false;
                }
            });
            $("#chkAll").attr("checked", ischeckAll);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="checkbox" id="chkAll" />全选
        <input type="checkbox" value="反选" />反选<br />
        <input type="checkbox" id="chkChild1" value="cf" />吃饭
        <input type="checkbox" id="chkChild2" value="sj" />睡觉
        <input type="checkbox" id="chkChild3" value="ddd" />打豆豆
    </div>
    </form>
</body>

</html>

原文地址:https://www.cnblogs.com/jiayue360/p/3168013.html