JS中attr和prop属性的区别以及优先选择示例介绍_基础知识
相比attr,prop是1.6.1才新出来的,两者从中文意思理解,都是获取/设置属性的方法(attributes和properties)。只是,window或document中使用.attr()方法在jQuery1.6之前不能正常运行,因为window和document中不能有attributes。prop应运而生了。
既然我们想知道他们两的区别,最好就看看他们的源代码,不要被代码长度所吓到,我们只看关键的几句:
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 ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }
prop方法代码(jQuery版本1.8.3)
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 ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }
attr方法里面,最关键的两行代码,elem.setAttribute( name, value + “” )和ret = elem.getAttribute( name ),很明显的看出来,使用的DOM的API setAttribute和getAttribute方法操作的属性元素节点。
而prop方法里面,最关键的两行代码,return ( elem[ name ] = value )和return elem[ name ],你可以理解成这样document.getElementById(el)[name] = value,这是转化成JS对象的一个属性。
既然明白了原理是这样,我们来看看一个例子:
<input type="checkbox" id="test" abc="111" />
$(function(){ el = $("#test"); console.log(el.attr("style")); //undefined console.log(el.prop("style")); //CSSStyleDeclaration对象 console.log(document.getElementById("test").style); //CSSStyleDeclaration对象 });
el.attr(“style”)输出undefined,因为attr是获取的这个对象属性节点的值,很显然此时没有这个属性节点,自然输出undefined
el.prop(“style”)输出CSSStyleDeclaration对象,对于一个DOM对象,是具有原生的style对象属性的,所以输出了style对象
至于document.getElementById(“test”).style和上面那条一样
接着看:
el.attr("abc","111") console.log(el.attr("abc")); //111 console.log(el.prop("abc")); //undefined
首先用attr方法给这个对象添加abc节点属性,值为111,可以看到html的结构也变了
el.attr(“abc”)输出结果为111,再正常不过了
el.prop(“abc”)输出undefined,因为abc是在这个的属性节点中,所以通过prop是取不到的
el.prop("abc", "222"); console.log(el.attr("abc")); //111 console.log(el.prop("abc")); //222
我们再用prop方法给这个对象设置了abc属性,值为222,可以看到html的结构是没有变化的。输出的结果就不解释了。
上面已经把原理讲清楚了,什么时候用什么就可以自己把握了。
提一下,在遇到要获取或设置checked,selected,readonly和disabled等属性时,用prop方法显然更好,比如像下面这样:
<input type="checkbox" id="test" checked="checked" />
console.log(el.attr("checked")); //checked console.log(el.prop("checked")); //true console.log(el.attr("disabled")); //undefined console.log(el.prop("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升级的时候大家要注意这点!
以下是官方建议attr(),prop()的使用:
以下是官方建议attr(),prop()的使用:

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题
![如何解决'[Vue warn]: Missing required prop”错误](https://img.php.cn/upload/article/000/887/227/169304743965914.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
如何解决“[Vuewarn]:Missingrequiredprop”错误在开发Vue应用程序时,有时会遇到一个常见的错误信息:“[Vuewarn]:Missingrequiredprop”。这个错误通常指的是在组件中缺少必需的属性值,导致组件无法正常渲染。解决这个问题的方法很简单,我们可以通过一些技巧和规范来避免和处理这个错误。以下是一些解
![解决'[Vue warn]: Invalid prop: invalid value”错误的方法](https://img.php.cn/upload/article/000/465/014/169294628931912.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
解决“[Vuewarn]:Invalidprop:invalidvalue”错误的方法在使用Vue.js开发应用程序时,我们经常会遇到一些错误和警告。其中一个常见的错误是“[Vuewarn]:Invalidprop:invalidvalue”。这个错误通常发生在我们尝试将无效的值传递给Vue组件的属性时。在本文中,我们将深入探讨该错误的原
![解决'[Vue warn]: Invalid prop: custom validator”错误的方法](https://img.php.cn/upload/article/000/000/164/169254319231018.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
解决“[Vuewarn]:Invalidprop:customvalidator”错误的方法在使用Vue开发过程中,我们时常会遇到一些警告和错误信息。其中一个常见的错误信息就是“[Vuewarn]:Invalidprop:customvalidator”。这个错误信息出现的原因是因为我们在使用自定义验证器函数时,未能正确地验证传递给组件
![如何解决'[Vue warn]: Invalid prop: type check”错误](https://img.php.cn/upload/article/000/887/227/169306085649427.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
如何解决“[Vuewarn]:Invalidprop:typecheck”错误Vue.js是一款流行的JavaScript框架,用于构建用户界面。在使用Vue.js开发应用程序时,我们有时会遇到一些错误信息,其中之一是“[Vuewarn]:Invalidprop:typecheck”。这个错误通常是由于我们在组件中错误使用了属性
![解决'[Vue warn]: Avoid mutating a prop directly”错误的方法](https://img.php.cn/upload/article/000/465/014/169226406590115.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
解决“[Vuewarn]:Avoidmutatingapropdirectly”错误的方法在使用Vue.js开发项目时,我们可能会遇到一个常见的警告信息:“[Vuewarn]:Avoidmutatingapropdirectly”。这个警告信息的意思是我们不应该直接改变一个props属性的值,而是应该通过触发事件,让父组件去改变pro
![如何处理'[Vue warn]: Avoid mutating a prop directly”错误](https://img.php.cn/upload/article/000/465/014/169224194948720.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
如何处理“[Vuewarn]:Avoidmutatingapropdirectly”错误当使用Vue.js开发Web应用程序时,我们经常会遇到一些警告或错误。其中一个常见的警告是“[Vuewarn]:Avoidmutatingapropdirectly”,这意味着我们在组件中直接修改了一个被父组件传递的属性(prop)。在本文中,我们
![解决'[Vue warn]: Invalid prop: update value”错误的方法](https://img.php.cn/upload/article/000/465/014/169305238381644.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
解决“[Vuewarn]:Invalidprop:updatevalue”错误的方法在Vue开发中,我们经常会遇到“[Vuewarn]:Invalidprop:updatevalue”错误。这个错误通常是由于父组件向子组件传递了一个无效的值引起的。虽然这个错误是Vue的警告而不是致命错误,但还是应该及时解决,以保证程序的健壮性。本文将介绍

Vue组件通讯中的多层级传递方案比较Vue是一款非常受欢迎的前端框架,它提供了一种组件化的开发方式,通过组件的嵌套和通讯,实现了复杂应用的开发。在实际开发中,组件之间的通讯常常是一个重要的问题。当组件之间存在多层级关系时,如何高效地传递数据成为了开发者需要思考的问题。本文将介绍几种常见的多层级组件通讯方案,并对它们进行比较。使用props和$emitVue提
