您的位置:首页 > 产品设计 > UI/UE

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

2015-03-17 14:40 441 查看
原来是jQuery版本问题。



Attributes vs. Properties

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

例如,
selectedIndex
,
tagName
,
nodeName
,
nodeType
,
ownerDocument
,
defaultChecked
,
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐