解决checkbox属性checked为true但是未被选中的问题

原来是jQuery版本问题。

Attributes vs. Properties

attributesproperties之间的差异在特定情况下是很重要。jQuery 1.6之前 ,.attr()方法在取某些 attribute 的值时,会返回 property 的值,这就导致了结果的不一致。从 jQuery 1.6 开始, .prop()方法 方法返回 property 的值,而.attr() 方法返回 attributes 的值。

例如, selectedIndextagNamenodeNamenodeTypeownerDocumentdefaultChecked, 和 defaultSelected应使用.prop()方法进行取值或赋值。 在jQuery1.6之前,这些属性使用.attr()方法取得,但是这并不是元素的attr属性。他们没有相应的属性(attributes),只有特性(property)。



<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<title>checkbox 全选 反选</title>
</head>
<body>
	<div class="warp" style="margin:100px">
		<div class="checktype">
			<label>全选<input type="radio" name="checktype" id="checkall" /></label>
			<label>反选<input type="radio" name="checktype" id="checkback" /></label>
		</div>
		<div class="checkbox">
			<table>
				<tr>
				    <td><input type="checkbox" />1</td>
				</tr>
				<tr>
				    <td><input type="checkbox" />2</td>
				</tr>
				<tr>
				    <td><input type="checkbox" />3</td>
				</tr>
				<tr>
				    <td><input type="checkbox" />4</td>
				</tr>
				<tr>
				    <td><input type="checkbox" />5</td>
				</tr>
				<tr>
				    <td><input type="checkbox" />6</td>
				</tr>
				<tr>
				    <td><input type="checkbox" />7</td>
				</tr>
			</table>
		</div>
	</div>
	<script type="text/javascript" src="../jquery-1.11.0.min.js"></script>
	<script type="text/javascript">
		$(function(){

			$("#checkall").click(function(){
				if(this.checked){
					$(".checkbox input[type=checkbox]").prop("checked",true);
				}else{
					$(".checkbox input[type=checkbox]").prop("checked",false);
				}
			});

			$("#checkback").click(function(){
				var back = $(".checkbox input[type=checkbox]");
				back.each(function(){
					console.log(this.checked);
					if( this.checked ){
						$(this).prop("checked",false);
					}else{
						$(this).prop("checked",true);
					}
					
				});
			});
		})
	</script>
</body>
</html>


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值