jQuery prop和attr的区别
两者对比
jquery方法 | 原理 | 适合场景 | 缺陷 |
prop | 解析原生property element.property | radio/checkbox select标签 等需要读boolean和索引的场合 | 读不到自定义属性 如<a my=’I’/> my属性读不到 |
attr | 通过Attr API去读取 element.getAttribute(propertyName) | 除prop场景外 | 可能读不到boolean或一些索引值 如checked,selectedIndex |
prop方法
例子
在控制台输入
document.getElementsByTagName('a')[0].href
控制台输出
"http://www.baidu.com/home/xman/show/liteoff"
href就是标签a映射的DOM对象HTMLAnchorElement的原生属性。
jQuery源码
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );//这里就是读原生property
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
}
attr方法
例子
在控制台输入
document.getElementsByTagName('a')[10].getAttribute('href')
控制台输出
"http://www.hao123.com"
getAttribute就是Attr类的查询API。其他还有删除、修改、增加。
jQuery源码
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );//这里通过Attr API读取属性
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
}
转载于//www.cnblogs.com/mominger/p/3978039.html
还没有评论,来说两句吧...