使用Jquery判断checkbox的选中方法.

页面代码:

<!DOCTYPE html>
<html>
<head>
		<title></title>
		<script src="./jquery-1.10.2.min.js"></script>
</head>
<body>
		<input type="checkbox" name="parent" />选择
		<ul>
				<li><input type="checkbox" name="child[]"/></li>
				<li><input type="checkbox" name="child[]"/></li>
				<li><input type="checkbox" name="child[]"/></li>
		</ul>

		<script>
				$(function(){
						$('input[name=parent]').click(function(){
								var checked = $(this).prop('checked');
								if ($(this).is(":checked")) {
										alert(333);  //点击选中的时候可以判断是否选中
								}

								if (checked == true) {
										alert(444);  //可以判断是否选中
								}

								if ($(this).attr('checked') == true) {
										alert(55);  //无法判断,返回的是undefined
								}
						});
				});

		</script>
</body>
</html>

使用js获取checkbox选中状态的时候,都是返回true 或者false.

设置选中状态,有两种方式可以实现,一使用prop 二使用attr

attr()

代码

<!DOCTYPE html>
<html>
<head>
		<title></title>
		<script src="./jquery-1.10.2.min.js"></script>
</head>
<body>
		<input type="checkbox" name="parent" />选择
		<ul>
				<li><input type="checkbox" name="child[]"/></li>
				<li><input type="checkbox" name="child[]"/></li>
				<li><input type="checkbox" name="child[]"/></li>
		</ul>

		<script>
				$(function(){
						$('input[name=parent]').click(function(){
								if ($(this).is(':checked')) {
										$('input[name^=child]').attr('checked',true);
								} else {
										$('input[name^=child]').attr('checked',false);
								}

						});
				});

		</script>
</body>
</html>

结果:

第一次勾选选择,ul>li里面的input可以选中
第二次勾选(即去除选中),ul>li里面的input可以取消选中
第三次勾选,ul>li无法选中了

具体原因有知道的烦请告知哈哈.

使用attr的坑,可以用prop弥补

prop()

代码

<!DOCTYPE html>
<html>
<head>
		<title></title>
		<script src="./jquery-1.10.2.min.js"></script>
</head>
<body>
		<input type="checkbox" name="parent" />选择
		<ul>
				<li><input type="checkbox" name="child[]"/></li>
				<li><input type="checkbox" name="child[]"/></li>
				<li><input type="checkbox" name="child[]"/></li>
		</ul>

		<script>
				$(function(){
						$('input[name=parent]').click(function(){
								if ($(this).is(':checked')) {
										$('input[name^=child]').prop('checked',true);  //此处有修改为prop方法
								} else {
										$('input[name^=child]').prop('checked',false);  //此处修改为prop方法
								}

						});
				});

		</script>
</body>
</html>

现在选多少次都可以实现效果了.