jquery判断checked的三种方法:
.attr('checked'): //看版本1.6+返回:"checked"或"undefined" ;1.5-返回:true或false
.prop('checked'): //16+:true/false
.is(':checked'): //所有版本:true/false//别忘记冒号哦
jquery赋值checked的几种写法:
所有的jquery版本都可以这样赋值:
// $("#cb1").attr("checked","checked");
// $("#cb1").attr("checked",true);
jquery1.6+:prop的4种赋值:
// $("#cb1").prop("checked",true);//很简单就不说了哦
// $("#cb1").prop({checked:true}); //map键值对
// $("#cb1").prop("checked",function(){
return true;//函数返回true或false
});
还有这种:$("#cb1").prop("checked","checked");
第一种案例(页面上的所有复选框都会包含):
<!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 runat="server">
<title>Index</title>
<script src="http://img.jb51.net/jslib/jquery/jquery14.js"></script>
<script type="text/javascript">
$(function() {
$("#CheckAll").click(function() {
if($("#CheckAll").attr("checked")){
//var flag = $(this).attr("checked");
// $("[name=subBox]:checkbox").each(function() { //根据名字进行选中
// $(this).attr("checked", flag);
//})
$(':checkbox').attr('checked','checked');
}else{
$(':checkbox').attr('checked','');
}
})
})
</script>
</head>
<body>
<div>
<input id="CheckAll" type="checkbox" />全选
<input name="subBox" type="checkbox" />周一
<input name="subBox" type="checkbox" />周二
<input name="subBox" type="checkbox" />周三
<input name="subBox" type="checkbox" />周四
</div>
</body>
</html>
第二种案例(只包含部分复选框的全选/全不选):
<!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 runat="server">
<title>Index</title>
<script src="http://img.jb51.net/jslib/jquery/jquery14.js"></script>
<script type="text/javascript">
$(function () {
$("#CheckAll").change(function () {
var ischecked = $(this).attr("checked");
$("input[name='subBox']").each(function () {
$("input[name='subBox']").attr("checked", ischecked)
$("#CheckAll").attr("checked", ischecked);
});
});
});//美术按地区查询高校库反选
</script>
</head>
<body>
<div>
<input id="CheckAll" type="checkbox" />全选
<input name="subBox" type="checkbox" />周一
<input name="subBox" type="checkbox" />周二
<input name="subBox" type="checkbox" />周三
<input name="subBox" type="checkbox" />周四
</div>
</body>
</html>
这种是根据名称name属性来判断的,同样的可以使用id、class选择器来进行操作。