日常问题记录--jquery中HTML元素本身固有属性用prop,自定义的DOM属性,在处理时,使用attr方法...

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

转载于:https://www.cnblogs.com/carterzhang/p/5326177.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值