1,jsp 页面
<body>
<input type="checkbox" id="selectAll" >全选</br>
</br>
<input type="checkbox" id="sid1">苹果</br>
<input type="checkbox" id="sid2">草莓</br>
<input type="checkbox" id="sid3">西瓜</br>
<input type="checkbox" id="sid4">菠萝</br>
</body>
2,js
<script>
$(function(){
//全选和全不选
$('#selectAll').bind('click',function(){
// alert(this.checked);//选中的时候返回true
//alert(this);//object HTMLInputElement
//alert($(this));//object Object
//alert($(this).prop('checked'));//true
//alert($(this).attr('checked'));//undefined
if(this.checked){ //全选
$("input[id^='sid']").each(function(){
$(this).prop('checked',true);
})
}else{ //全不选
$("input[id^='sid']").each(function(){
$(this).prop('checked',false);
})
}
});
//所有的子项选中或者不全选中后,全选按钮也选中或者不选中
var allLength=$("input[id^=sid]").length; //所有的checkbox的长度
$("input[id^=sid]").each(function(){
$(this).bind('click',function(){
var selectedLength=$("input[id^=sid]:checked").length;//所有的选中的checkbox的长度
if(selectedLength==allLength){
$('#selectAll').prop("checked",true);//全选按钮
}else{
$('#selectAll').prop("checked",false);
}
})
})
})
</script>