Jquery学习笔记(4)--checkbox全选反选

可能有浏览器兼容性,注意html里的checked是一个属性,存在就默认选中。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <script src='jquery.js'></script>
 7 </head>
 8 <body>
 9     <p><input type="checkbox">篮球</p>
10     <p><input type="checkbox">唱歌</p>
11     <p><input type="checkbox">旅游</p>
12     <p><input type="checkbox">美食</p>
13     <input type="button" value="全选" name="all">
14     <input type="button" value="全不选" name="none">
15     <input type="button" value="反选" name="reverse">
16     
17 </body>
18 <script>
19     //这个地方在谷歌浏览器有问题,点全不选后再点全选没有效果,ie里面没问题。
20     //checked在html里面是一个属性,不管checked=''里面是啥,都会默认选中。
21     $('[name=all]').click(function(){
22         $('p input').attr({'checked':true});
23     });
24     $('[name=none]').click(function(){
25         $('p input').removeAttr('checked',false);
26     });
27     $('[name=reverse]').click(function(){
28         $('p input').each(function(){
29             //这里使用js的this对象,checked是一个属性
30             this.checked = !this.checked;
31         });
32     });
33 </script>
34 </html>

 修改后,chrome也可以用了:

 1 <script>
 2     //这个地方在谷歌浏览器有问题,点全不选后再点全选没有效果,ie里面没问题。
 3     //checked在html里面是一个属性,不管checked=''里面是啥,都会默认选中。
 4     $('[name=all]').click(function(){
 5         //jqery负责遍历,js的this改变checked的true和false
 6         $('p input').each(function(){
 7             this.checked = true;
 8         });
 9     });
10     $('[name=none]').click(function(){
11         //同上 
12         $('p input').each(function(){
13             this.checked = false;
14         });
15         
16     });
17     $('[name=reverse]').click(function(){
18         $('p input').each(function(){
19             //这里使用js的this对象,checked是一个属性
20             // alert(!this.checked);
21             this.checked = !this.checked;
22         });
23     });
24 </script>
25 </html>

 再次改进,使用prop()方法,专门修改固有属性,比如checked:

 1 <script>
 2     $('[name=all]').click(function(){
 3         $(':checkbox').prop('checked',true);
 4     });
 5     $('[name=none]').click(function(){
 6         $(':checkbox').prop('checked',false);
 7     });
 8     $('[name=anti]').click(function(){
 9         $(':checkbox').each(function(){
10             var isTrue = !$(this).prop('checked');
11             // alert(isTrue);
12             $(this).prop('checked',isTrue);
13         });
14     });
15 </script>
原文地址:https://www.cnblogs.com/Jacklovely/p/6208341.html