今天打算用jQuery实现一下复选框的全选、全不选和反选问题,刚开始用的是attr("checked",true/false)方法,发现只能在最开始实现一次全选,可以实现全不选,无法实现反选,总之调试了好久死活得不到想要的效果。最后发现,jquery 1.7.2之前支持attr对固有属性的操作,后面的版本只能用prop了。详细了解jQuery中attr()和prop()的区别,请点击参考。
下面贴上我的代码以供参考:
复制代码
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>全选、全不选、反选</title>
6 <style type="text/css">
7 #choose input {
8 display: block;
9 }
10 </style>
11 <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
12 <script type="text/javascript">
13 $(function(){
14 var $choose = $("#choose input");
15 //全选
16 $("#all").click(function(){
17 $choose.each(function(){
18 $(this).prop("checked",true);
19 });
20 });
21 //全不选
22 $("#not").click(function(){
23 $choose.prop("checked",false);
24 });
25 //反选
26 $("#reverse").click(function(){
27 $choose.each(function(){
28 $(this).prop("checked",!$(this).prop("checked"));
29 });
30 });
31 });
32 </script>
33 </head>
34 <body>
35 <div id="box-function">
36 <input id="all" type="button" value="全选" />
37 <input id="not" type="button" value="全不选" />
38 <input id="reverse" type="button" value="反选" />
39 </div>
40
41 <div id="choose">
42 <input type="checkbox" />
43 <input type="checkbox" />
44 <input type="checkbox" />
45 <input type="checkbox" />
46 <input type="checkbox" />
47 <input type="checkbox" />
48 <input type="checkbox" />
49 <input type="checkbox" />
50 <input type="checkbox" />
51 <input type="checkbox" />
52 <input type="checkbox" />
53 <input type="checkbox" />
54 </div>
55 </body>
56 </html>
下面贴上我的代码以供参考:
复制代码
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>全选、全不选、反选</title>
6 <style type="text/css">
7 #choose input {
8 display: block;
9 }
10 </style>
11 <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
12 <script type="text/javascript">
13 $(function(){
14 var $choose = $("#choose input");
15 //全选
16 $("#all").click(function(){
17 $choose.each(function(){
18 $(this).prop("checked",true);
19 });
20 });
21 //全不选
22 $("#not").click(function(){
23 $choose.prop("checked",false);
24 });
25 //反选
26 $("#reverse").click(function(){
27 $choose.each(function(){
28 $(this).prop("checked",!$(this).prop("checked"));
29 });
30 });
31 });
32 </script>
33 </head>
34 <body>
35 <div id="box-function">
36 <input id="all" type="button" value="全选" />
37 <input id="not" type="button" value="全不选" />
38 <input id="reverse" type="button" value="反选" />
39 </div>
40
41 <div id="choose">
42 <input type="checkbox" />
43 <input type="checkbox" />
44 <input type="checkbox" />
45 <input type="checkbox" />
46 <input type="checkbox" />
47 <input type="checkbox" />
48 <input type="checkbox" />
49 <input type="checkbox" />
50 <input type="checkbox" />
51 <input type="checkbox" />
52 <input type="checkbox" />
53 <input type="checkbox" />
54 </div>
55 </body>
56 </html>