写个例子比较下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>
效果图:
如果给input添加checked属性
由此可知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() ) | √ |