jquery的全选/全不选/反选以及attr添加checked属性失败的解决办法

如下图:

 

 1 <head>
 2     <title></title>
 3     <style type="text/css">
 4         div
 5         {
 6             border: 1px solid black;
 7             width: 300px;
 8             height: 100px;
 9             padding: 10px 10px 10px 10px;
10             margin: 10px auto;
11         }
12     </style>
13     <script src="js/jquery-1.9.0.js" type="text/javascript"></script>
14     <script type="text/javascript">
15         $(function () {
16             $("#checkAllorNotAll").click(function () {
17                 //如果使用.attr()则前两次点击的时候有效,当第三次之后点击则无效了,使用.prop很好的解决了这个问题
18                 $(this).siblings("input[type=checkbox]").prop("checked", this.checked);
19             });
20 
21             //全选按钮
22             $("#checkAll").click(function () {
23                 $(this).siblings("input[type=checkbox]:not(#checkAllorNotAll)").prop("checked", true);
24             });
25 
26             //全不选按钮
27             $("#checkNotAll").click(function () {
28                 $(this).siblings("input[type=checkbox]:not(#checkAllorNotAll)").prop("checked", false);
29             });
30 
31             //反选按钮
32             $("#checkFan").click(function () {
33                 var $chList = $(this).siblings("input[type=checkbox]:not(#checkAllorNotAll)");
34                 $chList.each(function () {
35                     $(this).prop("checked", !this.checked);
36                 });
37             });
38 
39             //提交按钮
40             $("#btnSubmit").click(function (e) {
41                 e.preventDefault();
42                 var hobby = "您的爱好是: ";
43                 var $hobbys = $(this).siblings("input[type=checkbox]:not(#checkAllorNotAll)");
44                 $hobbys.each(function () {
45                     // alert(this);
46                     if (this.checked) {
47                         hobby += this.value + " ";
48                     }
49                 });
50                 alert(hobby);
51             });
52         });
53     </script>
54 </head>
55 <body>
56     <div>
57         <input type="checkbox" id="checkAllorNotAll" />全选/全不选<br />
58         <input type="checkbox" value="打篮球" name="che" />打篮球
59         <input type="checkbox" name="che" value="踢足球" />踢足球
60         <input type="checkbox" name="che" value="游泳" />游泳
61         <input type="checkbox" name="che" value="唱歌" />唱歌<br />
62         <input type="button" id="checkAll" value="全选" />
63         <input type="button" id="checkNotAll" value="全不选" />
64         <input type="button" id="checkFan" value="反选" />
65         <input type="button" id="btnSubmit" value="提交" />
66     </div>
67 </body>
jquery实现全选/全不选/反选代码

 

posted @ 2013-10-25 18:23  李亚杰  阅读(425)  评论(0编辑  收藏  举报