JS中attr和prop属性的区别

JS中attr和prop属性的区别,第1张

JS中attr和prop属性的区别

相比attr,prop是161才新出来的,两者从中文意思理解,都是获取/设定属性的方法(attributes和properties)。只是,window或document中使用attr()方法在jQuery16之前不能正常执行,因为window和document中不能有attributes。prop应运而生了。
既然我们想知道他们两的区别,最好就看看他们的原始码,不要被程式码长度所吓到,我们只看关键的几句:
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elemnodeType;
don't get/set attributes on text, ment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQueryisFunction( jQueryfn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
Fallback to prop when attributes are not supported
if ( typeof elemgetAttribute === "undefined" ) {
return jQueryprop( elem, name, value );
}
notxml = nType !== 1 || !jQueryisXMLDoc( elem );
All attributes are lowercase
Grab necessary hook if one is defined
if ( notxml ) {
name = nametoLowerCase();
hooks = jQueryattrHooks[ name ] || ( rbooleantest( name ) boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQueryremoveAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooksset( elem, value, name )) !== undefined ) {
return ret;
} else {
elemsetAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooksget( elem, name )) !== null ) {
return ret;
} else {
ret = elemgetAttribute( name );
Non-existent attributes return null, we normalize to undefined
return ret === null
undefined :
ret;
}
}
prop方法程式码(jQuery版本183)
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elemnodeType;
don't get/set properties on text, ment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQueryisXMLDoc( elem );
if ( notxml ) {
Fix name and attach hooks
name = jQuerypropFix[ name ] || name;
hooks = jQuerypropHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooksset( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooksget( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
}
attr方法里面,最关键的两行程式码,elemsetAttribute( name, value + “” )和ret = elemgetAttribute( name ),很明显的看出来,使用的DOM的API setAttribute和getAttribute方法 *** 作的属性元素节点。而prop方法里面,最关键的两行程式码,return ( elem[ name ] = value )和return elem[ name ],你可以理解成这样documentgetElementById(el)[name] = value,这是转化成JS物件的一个属性。
既然明白了原理是这样,我们来看看一个例子:
<input type=checkbox id="test" abc="111" />
$(function(){
el = $("#test");
consolelog(elattr("style")); undefined
consolelog(elprop("style")); CSSStyleDeclaration物件
consolelog(documentgetElementById("test")style); CSSStyleDeclaration物件
});
elattr(“style”)输出undefined,因为attr是获取的这个物件属性节点的值,很显然此时没有这个属性节点,自然输出undefinedelprop(“style”)输出CSSStyleDeclaration物件,对于一个DOM物件,是具有原生的style物件属性的,所以输出了style物件至于documentgetElementById(“test”)style和上面那条一样
接着看:
elattr("abc","111")
consolelog(elattr("abc")); 111
consolelog(elprop("abc")); undefined
首先用attr方法给这个物件新增abc节点属性,值为111,可以看到的结构也变了
elattr(“abc”)输出结果为111,再正常不过了elprop(“abc”)输出undefined,因为abc是在这个的属性节点中,所以通过prop是取不到的
elprop("abc", "222");
consolelog(elattr("abc")); 111
consolelog(elprop("abc")); 222
我们再用prop方法给这个物件设定了abc属性,值为222,可以看到的结构是没有变化的。输出的结果就不解释了。
上面已经把原理讲清楚了,什么时候用什么就可以自己把握了。
提一下,在遇到要获取或设定checked,selected,readonly和disabled等属性时,用prop方法显然更好,比如像下面这样:
<input type=checkbox id="test" checked="checked" />consolelog(elattr("checked")); checked
consolelog(elprop("checked")); true
consolelog(elattr("disabled")); undefined
consolelog(elprop("disabled")); false
显然,布林值比字串值让接下来的处理更合理。
PS一下,如果你有JS效能洁癖的话,显然prop的效能更高,因为attr需要访问DOM属性节点,访问DOM是最耗时的。这种情况适用于多选项全选和反选的情况。
大家都知道有的浏览器只要写disabled,checked就可以了,而有的要写成disabled = "disabled",checked="checked",比如用attr("checked")获取checkbox的checked属性时选中的时候可以取到值,值为"checked"但没选中获取值就是undefined。
jq提供新的方法“prop”来获取这些属性,就是来解决这个问题的,以前我们使用attr获取checked属性时返回"checked"和"",现在使用prop方法获取属性则统一返回true和false。
那么,什么时候使用attr(),什么时候使用prop()?1新增属性名称该属性就会生效应该使用prop();2是有true,false两个属性使用prop();3其他则使用attr();专案中jquery升级的时候大家要注意这点!

window或document中使用attr()方法在jQuery16中不能正常执行,因为window和document中不能有attributes。它们包含properties(比如:location或readyState)

举个简单的例子取值prop('checked')false布林值attr('checked')undefind获取的是字串赋值prop('new-attr',true)attr('new-attr',true)再次获取的prop还是布林值attr还是字串

window或document中使用attr()方法在jQuery16中不能正常执行,因为window和document中不能有attributes。它们包含properties(比如:location或readyState),必须使用prop()方法 *** 作或简单地使用javascript原生的方法。 在jQuery161中,wind

window或document中使用attr()方法在jQuery16中不能正常执行,因为window和document中不能有attributes。它们包含properties(比如:location或readyState),必须使用prop()方法 *** 作或简单地使用javascript原生的方法。 在jQuery161中,window和document中使用attr()将被自动转成使用prop(还没试过)。其次,checked,selected和前面提到的其它boolean attributes,因为这些attributes和其相应的properties之间的特殊关系而被特殊对待。通常,attribute 就是以下程式码中看到的,如:
<input type=”checkbox” checked=”checked”>
但它仅表示checked属性在页面载入的时候被设定成预设值或初始值,而不管checkbox元素是否被选中。 而通常 properties 是一个浏览器用来记录当前属性值的东西。正常情况下,properties反映它们相应的attributes。
所以,当用户点选一个checkbox元素或选中一个select元素的一个option时,使得properties保持最新,但对应的attributes却不一定,它仅被浏览器用来储存该属性的初始值。

对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
举例:
<a href="#" id="link1" action="delete">删除</a>
这个例子里<a>元素的DOM属性有“href、id和action”,很明显,前两个是固有属性,而后面一个“action”属性是我们自己自定义上去的,<a>元素本身是没有这个属性的。
因此获取action使用attr方式获取,其他需要通过prop方式获取
补充:
在jquery16之前的所有版本中都使用attr方法来获取

组成他们的字母不同

拼写不同

读音不同

看起来不同

以上就是关于JS中attr和prop属性的区别全部的内容,包括:JS中attr和prop属性的区别、、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/9747713.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-01
下一篇 2023-05-01

发表评论

登录后才能评论

评论列表(0条)

保存