<script type="text/javascript">
$(function() {
$("#select").click(function() {
if(this.checked){
$("input[name=Checkbox1]").each(function() {
$(this).prop("checked", true);
});
} else {
$("input[name=Checkbox1]").each(function() {
$(this).prop("checked", false);
});
}
});
});
$(function() {
$("#select").click(function() {
if(this.checked){
$("input[name=Checkbox1]").each(function() {
$(this).prop("checked", true);
});
} else {
$("input[name=Checkbox1]").each(function() {
$(this).prop("checked", false);
});
}
});
});
</script>
<input id="select" type="checkbox" />全选
<input id="select_reverse" type="checkbox" />反选
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
之前一直是用attr来进行设置,但是只能操作一次全选全不选,继续操作的话就无法实现!后面用prop方法才可以持续实现。
为什么jquery 1.6+增加了.prop()方法,因为在有些浏览器中比如说只要写disabled,checked就可以了,而有的要写成disabled = "disabled",checked="checked"。所以,从1.6开始,jq提供新的方法“prop”来获取这些属性。
以前我们使用attr获取checked属性时返回"checked"和"",现在使用prop方法获取属性则统一返回true和false。
那么,什么时候使用attr,什么时候使用prop??
1.添加属性名称该属性就会生效应该使用prop.
2.是有true,false两个属性使用prop.
3.其他则使用attr
项目中jquery升级的时候大家要注意这点!
以下是官方建议attr(),prop()的使用:
Attribute/Property | .attr() | .prop() |
---|---|---|
accesskey | √ | |
align | √ | |
async | √ | √ |
autofocus | √ | √ |
checked | √ | √ |
class | √ | |
contenteditable | √ | |
draggable | √ | |
href | √ | |
id | √ | |
label | √ | |
location ( i.e. window.location ) | √ | √ |
multiple | √ | √ |
readOnly | √ | √ |
rel | √ | |
selected | √ | √ |
src | √ | |
tabindex | √ | |
title | √ | |
type | √ | |
width ( if needed over .width() ) | √ |