jQuery中prop 和 attr 区别
prop() 方法是在jquery1.6中新添加的。我们知道 attr(“checked”)获取checkbox的checked属性时选中的时候可以取到值,值为”checked”但没选中获取值就是undefined。而现在使用prop方法获取属性则统一返回true和false。
那么具体的用法是什么,以下是个人理解
- 对于HTML元素本身就带有的固有属性,使用prop方法。
- 对于HTML元素我们自定义的DOM属性,使用attr方法。
注意:prop() 方法用于检索属性值,例如 DOM 属性(如 selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected)。
attr() 用于方法检索 HTML 属性$(“#chk1”).prop(“checked”) == false
$(“#chk2”).prop(“checked”) == true
如果上面使用attr方法,则会出现:
$("#chk1").attr("checked") == undefined
$("#chk2").attr("checked") == "checked"
以下是官方建议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() ) √
还没有评论,来说两句吧...