原作者:http://blog.csdn.net/szwangdf/article/details/42964399
相比attr,prop是1.6.1才新出来的,两者从中文意思理解,都是获取/设置属性的方法(attributes和properties)。只是,window或document中使用.attr()方法在jQuery1.6之前不能正常运行,因为window和document中不能有attributes。prop应运而生了。
之前看网上对比两者的文章,更是列出一个表来区分什么标签下使用prop,什么标签下使用attr,原谅我是懒惰的人,最害怕要背的东西,所以只有自己想想办法了。
既然我们想知道他们两的区别,最好就看看他们的源代码,不要被代码长度所吓到,我们只看关键的几句:
attr方法代码(jQuery版本1.8.3)
- 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是最耗时的。这种情况适用于多选项全选和反选的情况。
相关推荐
只是,window或document中使用.attr()方法在jQuery1.6之前不能正常运行,因为window和document中不能有attributes。prop应运而生了。 既然我们想知道他们两的区别,最好就看看他们的源代码,不要被代码长度所吓到,...
attribute和property都可以翻译为属性,为了以示区别,通常把这两个单词翻译为属性与特性。 ”test”>Click Here 上面这段HTML语句中有三个节点,分别是Element “div”、attribute “id”、Text “click here”,...
今天在项目中使用<select></select>下拉菜单时,使用juery操作,使页面加载完菜单默认选中的值为2,我一开始的操作如下: <!--html部分--> <select> <option value=1>1 <option value=2>2 ...
在jQuery 1.6, .prop()方法提供了一种明确检索属性值,同时.attr()检索的属性而已。 例如,考虑一个DOM元素的HTML标记中定义的<input type="checkbox" checked="checked" /> ,并假设它是一个JavaScript变量命名的...
#9255:修复webkit内核浏览器中jQuery.parseXML不能处理异常的问题。 #9854:Pass statusText through instead of “normalizing” it #9887:修复jQuery.ajaxSetup可能导致内存浪费的问题。 #9970:Typo in ajax.js...
jquery需要的所有js文件 /*! * jQuery UI 1.8.18 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * ...
一、jquery常用的事件 click(),dbclick() focus(),blur() change() keydown(),keypress(),keyup() mousedown(),mouseup()...三、jquery实现全选功能(重点是属性用.prop(),不用.attr()) 代码如下: <!DOCTY
本文实例讲述了js判断复选框是否选中的方法。分享给大家供大家参考,具体如下: 代码 //设置选中 $('#check1').prop('checked', true); //是否选中 var isChecked = $('#cb').prop('checked'); //或 var ...
在jQuery的attr与prop提到过在IE9之前版本中如果使用property不当会造成内存泄露问题,而且关于Attribute和Property的区别也让人十分头痛,在HTML5中添加了data-*的方式来自定义属性,所谓data-*实际上上就是data-...
if ($field.prop("checked")) { $field.attr("checked", "checked"); } } else { $field.attr("value", $field.val()); } }); copy.find("select").each(function () { var $field = $(this); $field.find...
特征适用于文本和密码输入仅在用户开始输入时隐藏占位符$ .fn.val和$ .fn.prop正确获取/设置值$ .fn.attr()正确获取/设置占位符属性支持AMD用法 $('[placeholder]').placeholder(options)选项force (boolean, ...
我当时就是简单的实现了,然后想封装到公共的js中,封装的太烂,不好意思贴出来了(就是把实现代码之间放到公共js中,然后每个页面都用固定的id,class,现在想想我都不好意思叫他封装了),然后想到之前老大有写过...
02 jquery循环方法和attr,prop方法 03 jquery模态对话框与clone的应用 04 jqueryCSS操作之offsets,position以及scrolltop 05 jquery事件绑定与事件委托 06 jquery动画效果 07 jquery扩展与插件 08 jquery扩展补充 09...
我当时就是简单的实现了,然后想封装到公共的js中,封装的太烂,不好意思贴出来了(就是把实现代码之间放到公共js中,然后每个页面都用固定的id,class,现在想想我都不好意思叫他封装了),然后想到之前老大有写过...
解决办法: 代码如下: $(‘input[type=”checkbox”]’).bind(‘click’,function() { $(this).prop(‘checked’).checkboxradio(“refresh”); // 绑定事件及时更新checkbox的checked值 }); 如果要用js去改变...
├─(28) 02 python s3 day44 jquery循环方法和attr,prop方法.avi ├─(29) 03 python s3 day44 jquery模态对话框与clone的应用.avi ├─(30) 04 python s3 day44 jqueryCSS操作之offsets,position以及scrolltop.avi...