jquery attr()与prop()的区别

本文通过示例对比了jQuery中attr()与prop()方法在处理checked等布尔属性时的不同表现。并根据官方建议总结了两种方法在不同场景下的适用性。

写个例子比较下attr()与prop()的差异

<body>
   <input type="radio" name="radio1" class="radio-btn">
   <label>男</label>
   <script type="text/javascript">
      $(document).ready(function(){
        // attr()获取的checked
         var checkedAttr=$(".radio-btn").attr("checked");
         console.log("attr()获取的值---------"+checkedAttr);
         // prop()获取的checked
         var checkedProp=$(".radio-btn").prop("checked");
         console.log("prop()获取的值---------"+checkedProp);
      });
   </script>
</body>

效果图:

193303_NzOi_3680343.png193307_m4JH_3680343.png

如果给input添加checked属性

193331_1GX6_3680343.png193334_jdF7_3680343.png

由此可知prop()方法获取属性统一返回true或false,attr()则返回undefined或checked

在做项目中,我遇到了使用attr()方法禁用单选按钮点击事件失效的问题,后来翻看好多资料,显示jquery版本在1.6+以上就用prop()代替了attr(),特别是如checked, selected 或者 disabled这一类的属性(具有true和false两个属性值的属性),最好使用prop()方法,其他的可以使用attr()方法

以下是官方建议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() ) 

 

 

 

 

转载于:https://my.oschina.net/u/3680343/blog/1592277

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值