今天一个同事需要实现这么一个效果,于是就测试了一下,中间的逻辑用了狠长时间,不过最终还是搞出来了!代码有点臃肿,没时间优化,有用到类似功能的朋友可以自己优化一下!(需加入自己的jquery文件)全选与取消全选
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>全选与取消全选</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var checkInfo = function(objname){
var cobjarr;
var pobjarr;
var operate = '_'; //ID连接符
if ( typeof($('#'+objname+operate+'1').attr('id')) !== 'undefined' ){
cobjarr = $('input[id^='+objname+operate+']');
$(cobjarr).each( function(){
$(this).attr('checked',$('#'+objname).attr('checked'));
});
}
if ( objname.indexOf(operate,0) == 1 ){
var newobjarr = objname.split(operate);
for( var k = newobjarr.length-1; k > 0; k-- ) {
newstr = '';
for ( var i = 0; i < k; i++ ){
newstr += newobjarr[i] + operate;
}
pobjarr = $('input[id^='+newstr+']');
j = 0;
$(pobjarr).each( function(){
if ( !$(this).attr('checked') ){
j++;
}
});
newstr2 = newstr.substr(0,newstr.length-1);
if ( j != 0 ){
$('#'+newstr2).attr('checked',false);
}else{
$('#'+newstr2).attr('checked',true);
}
}
}
}
</script>
</head>
<body>
<input id="a" name="a" type="checkbox" onclick="javascript:checkInfo(this.name);" />*<br />
<input id="a_1" name="a_1" type="checkbox" onclick="javascript:checkInfo(this.name);"/>一级_1 <input id="a_2" name="a_2" type="checkbox" onclick="javascript:checkInfo(this.name);" />一级_2<br />
<input id="a_1_1" name="a_1_1" type="checkbox" onclick="javascript:checkInfo(this.name);" />二级_1_1 <input id="a_1_2" name="a_1_2" type="checkbox" onclick="javascript:checkInfo(this.name);" />二级_1_2
<input id="a_2_1" name="a_2_1" type="checkbox" onclick="javascript:checkInfo(this.name);" />二级_2_1 <input id="a_2_2" name="a_2_2" type="checkbox" onclick="javascript:checkInfo(this.name);" />二级_2_2
<br />
<input id="a_1_1_1" name="a_1_1_1" type="checkbox" onclick="javascript:checkInfo(this.name);" />三级_1_1_1 <input id="a_1_2_1" name="a_1_2_1" type="checkbox" onclick="javascript:checkInfo(this.name);" />三级_1_2_1
<input id="a_2_1_1" name="a_2_1_1" type="checkbox" onclick="javascript:checkInfo(this.name);" />三级_2_1_1 <input id="a_2_2_1" name="a_2_2_1" type="checkbox" onclick="javascript:checkInfo(this.name);" />三级_2_2_1
<br />
</body>
</html>