jquery中,在设置多个radio的唯一选中时,prop与attr表现不同。次啊面代码中如果将prop换为attr,则页面所有checkbox在取消选中后,都不能再次选中;
原因:
- 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
- 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
<script language="javascript">
<!--
function checkBox(obj) {
// 只有当选中的时候才会去掉其他已经勾选的checkbox,所以这里只判断选中的情况
if (obj.is(":checked")) {
// 先把所有的checkbox 都设置为不选种
$('input.mybox').prop('checked', false);
// 把自己设置为选中
obj.prop('checked',true);
}
}
//-->
</script>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
<input type="checkbox" class="mybox" οnclick="checkBox($(this));"/>
再举一个例子:
<input id="chk1" type="checkbox" />是否可见
<input id="chk2" type="checkbox" checked="checked" />是否可见
像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。
$("#chk1").prop("checked") == false $("#chk2").prop("checked") == true
如果上面使用attr方法,则会出现:
$("#chk1").attr("checked") == undefined $("#chk2").attr("checked") == "checked