由于在网上不好找写的很全的,所以我就研究了一下,此代码是小弟的一点简化写法,注意在全选的id起名字的时候千万别和子的checkbox 的 Id有类似之处,不然出现麻烦,调试累死你哦。呵呵。我的就是,全选id=chkAll  子id=chk0 id=chk1 。。。这样会出现问题,就是当子全部选中的时候,全选的checkbox不会被选中哦,当然,我指的是用我的代码,你自己写的话,或许,不会错哦,提醒。提醒而已。。。不说了,上代码了,仅供参考

 <head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(
function () {

//全选
$("#checkAll").click(function () {
//获取字checkbox 中id 含有chk的将其设置为和全选状态一致
$(":checkbox[id*=chk]").attr("checked", $("#checkAll").attr("checked"));
});
//选子的checkbox判断全选的状态
$(":checkbox[id*=chk]").click(function () {

SingleCheck();
});
//反选
$(":button[value=反选]").click(function () {
$(
":checkbox[id*=chk]").each(function () {
//当被选中时,设置他不选中,简化了If...else...写法
$(this).attr("checked", !$(this).attr("checked"));
});
//判断全选状态
SingleCheck();
});
})

//携通用代码,判断全选状态
function SingleCheck() {
//假设所有的checkbox都被选中
var isCheckAll = true;
var i = 0;
$(
":checkbox[id*=chk]").each(function () {
//如果一个没有被选中
if (!$(this).attr("checked")) {
isCheckAll
= false;

//return true 相当于 continue
//return false 相当于 break
return false;
}
})
//设置全选的状态
$("#checkAll").attr("checked", isCheckAll);
}
</script>
</head>
<body>
全选<input type="checkbox" name="name" id="checkAll" />
反选<input type="button" name="name" value="反选" id="fanxuan" />
<input type="checkbox" name="name" id="chk0" />
<input type="checkbox" name="name" id="chk1" />
<input type="checkbox" name="name" id="chk2" />
</body>
</html>

补充bug,这段代码经过使用之后jquery1.6之前可以正常使用,juqery1.6+貌似获取选中值的时候有问题
问题如下,问度娘很多,发现一个大卡说了一个这个问题

elem.checked true (Boolean) Will change with checkbox state
$( elem ).prop( "checked" ) true (Boolean) Will change with checkbox state
elem.getAttribute( "checked" ) "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6) "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6.1+) "checked" (String) Will change with checkbox state
$( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state
而我这里需要的就是true 或者false,

把这里attr获取值的时候改成prop即可,问题解决,$( "#checkAll").prop( "checked" ),至于什么意思没去深究,有大神的话可以告知小弟
 

 

posted on 2011-12-03 21:32  幻想时空  阅读(1119)  评论(0编辑  收藏  举报