前几天,有人给 Multiple Select 插件 提了问题:

setSelects doesn't work in Firefox when using jquery 1.9.0

一直都在用 jQuery 1.8.3 的版本,没有尝试过 jQuery 1.9.0 的版本。

于是,开始调试代码,在 1.9.0 的版本中:

<input type="checkbox" />
<script>
$(function() {
$('input').click(function() {
$(this).attr('checked');
});
});
</script>

点击 checkbox,结果都是 undefined

而在 1.8.3 的版本中,结果是 checked 和 undefined

到这里,问题答案找到了,就是使用 attr() 方法的问题,于是查看官方文档, 才知道从 jQuery 1.6 开始新增了一个方法 prop(),但是一直都没有使用过。

从中文意思看,两者分别是获取/设置 attributes 和 properties 的方法,那么为什么还要增加 prop() 方法呢?

Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior.

因为在 jQuery 1.6 之前,使用 attr() 有时候会出现不一致的行为。

那么,什么时候使用attr(),什么时候使用prop()?

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method. 

根据官方的建议:具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr()

到此,将 attr('checked') 改成 prop('checked') 即可修复提的 issues 了。

^_^

等等,貌似问题还没真正解决,为什么开头例子中 jQuery 1.8.3 和 1.9.0 使用 attr() 会有所区别呢?

想知道他们的区别,最好的办法还是看他们的源代码:

1.8.3 attr():

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;
}
}

1.9.0 attr():

    attr: function( elem, name, value ) {
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;
} // 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 ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret; } else {
elem.setAttribute( name, value + "" );
return value;
} } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if ( typeof elem.getAttribute !== "undefined" ) {
ret = elem.getAttribute( name );
} // Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
}

1.8.3 和 1.9.0 的 prop() 是一样的:

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() 和 prop() 的区别

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,这是转化成 element 的一个属性。

对比调试 1.9.0 和 1.8.3 的 attr() 方法,发现两者的区别在于

hooks.get( elem, name )) 

返回的值不一样,具体的实现:

1.8.3 中

boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
}
}

1.9.0 中

boolHook = {
get: function( elem, name ) {
var
// Use .prop to determine if this attribute is understood as boolean
prop = jQuery.prop( elem, name ), // Fetch it accordingly
attr = typeof prop === "boolean" && elem.getAttribute( name ),
detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ?
attr != null :
// oldIE fabricates an empty string for missing boolean attributes
// and conflates checked/selected into attroperties
ruseDefault.test( name ) ?
elem[ jQuery.camelCase( "default-" + name ) ] :
!!attr : // fetch an attribute node for properties not recognized as boolean
elem.getAttributeNode( name ); return detail && detail.value !== false ?
name.toLowerCase() :
undefined;
}
}

由此可见,1.9.0 开始不建议使用 attr() 来对具有 true 和 false 两个属性的属性进行操作了。

那么我们的结论是:

具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr(),具体见下表:


注:本文中的大部分观点以及例子属于个人理解,难免还有不准确的地方,欢迎有相关研究的同行指正。

jQuery 中 attr() 和 prop() 方法的区别<转>的更多相关文章

  1. jQuery中attr和prop方法的区别

    jQuery中attr和prop方法的区别。 http://my.oschina.net/bosscheng/blog/125833 http://www.javascript100.com/?p=8 ...

  2. jQuery中attr和prop方法的区别说明

    jquery中attr和prop的基本区别可以理解为:如果是内置属性,建议用prop,如果是自定义的建议用attr. 例如 <input type=check  node=123 id=ck & ...

  3. jQuery 中 attr() 和 prop() 方法的区别

    前几天,有人给 Multiple Select 插件 提了问题: setSelects doesn't work in Firefox when using jquery 1.9.0 一直都在用 jQ ...

  4. jquery中attr和prop的区别、 什么时候用 attr 什么时候用 prop (转自 芈老头 )

    jquery中attr和prop的区别. 什么时候用 attr 什么时候用 prop   在高版本的jquery引入prop方法后,什么时候该用prop?什么时候用attr?它们两个之间有什么区别?这 ...

  5. jQuery中.attr()和.prop()的区别

    之前学习jQuery的时候,学习到了两种取得标签的属性值的方法:一种是elemJobj.attr(),另一种是elemJobj.prop().而在学习JS的时候,只有一种方法elemObj.getAt ...

  6. jquery中attr和prop的区别(转)

    在网络上看到这样一篇关于jquery中attr和prop的区别文章,觉得不错,所以转载了. 在jQuery 1.6中,.attr()方法查询那些没有设置的属性,则会返回一个undefined.如果你要 ...

  7. jquery中attr()与prop()函数用法实例详解(附用法区别)

    本文实例讲述了jQuery中attr()与prop()函数用法.分享给大家供大家参考,具体如下: 一.jQuery的attr()方法 jquery中用attr()方法来获取和设置元素属性,attr是a ...

  8. jquery中attr和prop的区别分析

    这篇文章主要介绍了jquery中attr和prop的区别分析的相关资料,需要的朋友可以参考下 在高版本的jquery引入prop方法后,什么时候该用prop?什么时候用attr?它们两个之间有什么区别 ...

  9. Jquery学习笔记(6)--jquery中attr和prop的区别【精辟】

    jquery中attr和prop的区别 在高版本的jquery引入prop方法后,什么时候该用prop?什么时候用attr?它们两个之间有什么区别?这些问题就出现了. 关于它们两个的区别,网上的答案很 ...

随机推荐

  1. DRP——JDBC中的Batch

    在jdbc2.0里添加了批量处理的功能(batch),其同意将多个sql语句作为一个单元送至数据库去运行,这样做能够提高操作效率.在操作大量的数据时, ORM框架实现批量是非常慢的.我们能够使用jdb ...

  2. Node Server零基础——开发环境文件自动重载

    收录待用,修改转载已取得腾讯云授权 前言 在 web 前端开发中,我们会借助 Grunt.Gulp 和 Webpack 等工具的 Watch 模块去监听文件变化,那服务端应该怎么做?其实文件变化的监听 ...

  3. Android程序的反编译对抗研究

    转自: http://www.freebuf.com/tools/76884.html 一.前言 对抗反编译是指让apk文件或者dex文件无法正常通过反编译工具,而且有可能导致工具异常或者崩溃,如ap ...

  4. 使用apache-cxf-2.2.10来制作一个极简版WebService程序

    原想拿最新版cxf来制作的,无奈Apache的zip包总下不下来,国内的apache-cxf-2.2.10却一蹴而就,也就用了这个版本.下载地址是:http://pan.baidu.com/s/1td ...

  5. (LeetCode 53)Maximum Subarray

    Find the contiguous subarray within an array (containing at least one number) which has the largest ...

  6. 魔术布局效果-使用本地JSON数据提供数据服务

    在线演示 有社区朋友不知道如何修改外部OpenAPI为本地的JSON服务,这里做一个简单演示. 阅读原文:魔术布局效果-使用本地JSON数据提供数据服务

  7. hdu 5247 找连续数(思维)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5247 找连续数 Time Limit: 2000/1000 MS (Java/Others)    M ...

  8. 网络地址转换相关函数使用(inet_addr,inet_ntoa,inet_addr)

    aa 相关函数原型及参数类型: 函数原型:int inet_aton(const char *cp, struct in_addr *inp); in_addr_t inet_addr(const c ...

  9. ScriptableObject 对象化的运用

    http://www.cnblogs.com/oldman/articles/2409554.html using UnityEngine; using UnityEditor; using Syst ...

  10. 在 HTML 中使用JavaScript

    <script>元素 属性     async:可选.async 属性规定一旦脚本可用,则会异步执行,表示应该立即下载脚本,但不妨碍页面中的其他操作,比如下载其他资源或等待加载其他脚本.a ...