1 <input type="checkbox" id="all" />全选<br />
2 <input type="checkbox" name="sub" />image1.jpg<br />
3 <input type="checkbox" name="sub"/>image2.jpg<br />
4 <input type="checkbox" name="sub"/>image3.jpg<br />
5 <input type="checkbox" name="sub"/>image4.jpg<br />
6 <script type="text/javascript">
7 $(function() {
8 $(\'#all\').on(\'click\',function(){
9 if(this.checked) {
10 $("input[name=\'sub\']").attr(\'checked\',true);
11 }else {
12 $("input[name=\'sub\']").attr(\'checked\',false);
13 }
14 });
15 });
16 </script>
用这个方法,在实现全选和取消全选中遇到了一个问题(这个问题出现在用jquery等动态添加内容时,点击全选后,再次点击取消全选,再次点击全选就不管用了,代码是这样的:
1 $("#left").append(
2 "<span>" + "全选" + "</span>" + "<input type=\"checkbox\" name=\"all\" id=\"all\">");
3 $.each(json.filelist,function(i, item) {
4 $("#left").append(
5 "<span>" + item.name + "</span>" + "<input type=\"checkbox\" name=\"sub\">" + "</br>");
});
在这种情况下,我又找到另外一种方法:
1 $("#all").on(\'click\',function() {
2 $("input[name=\'sub\']").prop("checked", this.checked);
3 });
4
5 $("input[name=\'sub\']").on(\'click\',function() {
6 var $subs = $("input[name=\'sub\']");
7 $("#all").prop("checked" , $subs.length == $subs.filter(":checked").length ? true :false);
8 });
推荐使用on绑定点击事件,因为on事件也适用于动态加载的元素