您的位置:首页 > 运维架构

简述jq中attr()和prop()的区别

2017-03-12 21:02 281 查看
attr,prop都是属性的意思,那他们有什么区别呢?我们先来看一下jquery的部分源码:

attr部分:

1 attr: function( elem, name, value, pass ) {
2 var ret, hooks, notxml,
3 nType = elem.nodeType;
4 // don't get/set attributes on text, comment and attribute nodes
5 if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
6 return;
7 }
8 if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
9 return jQuery( elem )[ name ]( value );
10 }
11 // Fallback to prop when attributes are not supported
12 if ( typeof elem.getAttribute === "undefined" ) {
13 return jQuery.prop( elem, name, value );
14 }
15 notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
16 // All attributes are lowercase
17 // Grab necessary hook if one is defined
18 if ( notxml ) {
19 name = name.toLowerCase();
20 hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
21 }
22 if ( value !== undefined ) {
23 if ( value === null ) {
24 jQuery.removeAttr( elem, name );
25 return;
26 } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
27 return ret;
28 } else {
29 elem.setAttribute( name, value + "" );
30 return value;
31 }
32 } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
33 return ret;
34 } else {
35 ret = elem.getAttribute( name );
36 // Non-existent attributes return null, we normalize to undefined
37 return ret === null ?
38 undefined :
39 ret;
40 }
41 }


prop部分:

1 prop: function( elem, name, value ) {
2 var ret, hooks, notxml,
3 nType = elem.nodeType;
4 // don't get/set properties on text, comment and attribute nodes
5 if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
6 return;
7 }
8 notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
9 if ( notxml ) {
10 // Fix name and attach hooks
11 name = jQuery.propFix[ name ] || name;
12 hooks = jQuery.propHooks[ name ];
13 }
14 if ( value !== undefined ) {
15 if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
16 return ret;
17 } else {
18 return ( elem[ name ] = value );
19 }
20 } else {
21 if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
22 return ret;
23 } else {
24 return elem[ name ];
25 }
26 }
27 }


我们注意到,两个方法最主要的源码部分是:attr是通过setAtrribute和getAttribute来设置的,使用的是DOM属性节点,而prop是通过document.getElementById(el)[name] = value来设置的,是转化为js对象的属性。

通常在获取或者设置checked,selected,readonly,disabled等的时候使用prop效果更好,减少了访问dom属性节点的频率。

大家知道,有的浏览器只要写checked,disabled就可以了,而有的则需要些checked=“checked”,disabled=“disabled”。比如用attr来获取checked,选中状态获取attr(“checked”)为checked,没有选中则为undefined。。而prop来获取的为,选中为true,没有选中为false。

另外,用prop来设置属性名,html结构是不会发生变化的。而用attr来设置属性名,html结构是会发生变化的。

总的来说,按照我自己的理解,一般如果是标签自身自带的属性,我们用prop方法来获取;如果是自定义的属性,我们用attr方法来获取。

参考链接:http://www.jb51.net/article/51688.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: