jQuery中attr和prop方法的区别

如题所述

也就是1.6版本以后将以前的attr混淆的部分区分开来。


下面是关于jQuery1.6和1.6.1中Attributes模块变化的描述,以及.attr()方法和.prop()方法的首选使用 

Attributes模块的变化是移除了attributes和properties之间模棱两可的东西,但是在jQuery社区中引起了一些混乱,因为在1.6之前的所有版本中都使用一个方法(.attr())来处理attributes和properties。但是老的.attr()方法有一些bug,很难维护。jQuery1.6.1对Attributes模块进行了更新,并且修复了几个bug。 

elem.checked true (Boolean) Will change with checkbox state 
$(elem).prop("checked") true (Boolean) Will change with checkbox state 
elem.getAttribute("checked") "checked" (String) Initial state of the checkbox; does not change 
$(elem).attr("checked")(1.6) "checked" (String) Initial state of the checkbox; does not change 
$(elem).attr("checked")(1.6.1+) "checked" (String) Will change with checkbox state 
$(elem).attr("checked")(pre-1.6) true (Boolean) Changed with checkbox state 

if ( elem.checked ) 
if ( $(elem).prop("checked") ) 
if ( $(elem).is(":checked") ) 

这三个都是返回Boolean值


下面是一个图表,可以很清楚知道哪些地方改用prop 哪些用attr。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-01-17
"从jQuery 1.6开始,新加入了一个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() ) √
个人简要总结了一下:
1、赋值时候,如果是<input type=""checkbox"" checked>这样的只有属性名就能生效的属性
推荐prop,即:$('input').prop('checked',true);
同时,false表示取消,即:$('input').prop('checked',false);
当然attr也行的:$('input').attr('checked','这里写什么都行的');
取消属性就是移除:$('input').removeAttr('checked');
2、取值的时候,如果是<input id=""input1"" type=""checkbox"" checked><input id=""input2"" type=""checkbox"">
推荐使用prop,即:
$('#input1').prop('checked'); //返回true
$('#input2').prop('checked'); //返回false
而使用attr,则:
$('#input1').attr('checked'); //返回checked
$('#input2').attr('checked'); //返回undefined
3、特殊属性赋值取值
这个特殊说明下,获取很多人都用不到呢。
比如需要在input中追加一个data-tips属性。变成这样子 <input type=""text"" value="""" data-tips=""aa"">
这时候只能写:$('input').attr('data-tips','aa');
使用prop是不管用的。
但是读值时候,两个都可以的:
$('input').attr('data-tips');//返回aa
$('input').prop('data-tips');//返回aa
"
相似回答