Differences between attr () and prop () methods in JQuery < goto >

Source: Internet
Author: User

A few days ago, someone asked the multiple Select plugin a question:

Setselects doesn ' t work in Firefox when using jquery 1.9.0

have been using the jquery 1.8.3 version and have not tried the jquery 1.9.0 version.

So, start debugging the code, in the 1.9.0 version:

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

Click CheckBox and the result is undefined

In the 1.8.3 version, the result is checked and undefined

Here, the answer to the question, is to use the attr () method, and then look at the official documents, only to know from JQuery 1.6 A new method prop (), but has not been used.

From the Chinese meaning, the two are the methods of acquiring/setting attributes and properties, so why increase the prop () method?

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

Because before JQuery 1.6, using attr () sometimes inconsistent behavior occurs.

So, when to use attr (), when to use Prop ()?

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

According to the official recommendation: properties with True and false two properties, such as checked, selected or disabled use prop (), other use attr ()

To this, change attr (' checked ') to prop (' checked ') to fix the issues.

^_^

Wait, it seems that the problem has not really solved, why the first example of JQuery 1.8.3 and 1.9.0 use attr () will be different?

To know their differences, the best way is to look at their source code:

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 nodesif (!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 is not supportedif (typeof Elem.getattribute = = ="Undefined") {Return Jquery.prop (Elem, name,Value); } notxml = NType!==1 | | !jquery.isxmldoc (Elem);All attributes is lowercaseGrab necessary Hook if one is definedif (notxml) {name = Name.tolowercase (); hooks = jquery.attrhooks[Name] | | (Rboolean.test (name)? boolhook:nodehook); }if (Value!== undefined) {if (Value = =NULL) {jquery.removeattr (elem, name);Return }Elseif (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 nodesif (!elem | | nType = = =3 | | NType = = =8 | | NType = = =2) {Return }Fallback to prop when attributes is not supportedif (typeof Elem.getattribute = = ="Undefined") {Return Jquery.prop (Elem, name,Value); } notxml = NType!==1 | | !jquery.isxmldoc (Elem);All attributes is lowercaseGrab necessary Hook if one is definedif (notxml) {name = Name.tolowercase (); hooks = jquery.attrhooks[Name] | | (Rboolean.test (name)? boolhook:nodehook); }if (Value!== undefined) {if (Value = =NULL) {jquery.removeattr (elem, name);}Elseif (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" span class= "keyword" >in hooks && (ret = hooks. Get (Elem, name))!== null) {return ret;} else {//in ie9+, Flash objects don ' t has. getattribute (#12945) //support:ie9+ if (typeof elem.getattribute!== //non-existent attributes return null, we normalize to undefined return ret = = null? Undefined:ret;}}           

1.8.3 and 1.9.0 's prop () are the same:

Prop:function (Elem, name,Value) {var ret, hooks, notxml, nType = Elem.nodetype;Don ' t get/set properties on text, comment and attribute nodesif (!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];             }}} 

First, let's look at the difference between attr () and prop () :

attr (), the two most critical lines of code

value + "" ); ret =  elem.getAttribute( name );

It is obvious to see that the DOM API SetAttribute () and the GetAttribute () method manipulate the attribute element nodes.

Prop (), the two most critical lines of code

return ( elem[ name ] = value );return elem[ name ];

It can be understood as document.getElementById (EL) [Name] = value, which is a property converted into element.

Compare Debug 1.9.0 and 1.8.3 's attr () method to find the difference between

hooks.get( elem, name )) 

The returned values are not the same, the specific implementation:

In 1.8.3

boolHook = {    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; }}

In 1.9.0

Boolhook = {Get:function (Elem, name) {VarUse. Prop to determine if the 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 Attribu TES //and conflates checked/selected into Attroperties rusedefault.test (name)? elem[Jquery.came LCase ( "default-" + name)]:!! attr: //fetch an attribute node for properties not recognized as Boolean Elem.getattributenode (NA ME); return detail && detail. value!== false? name.tolowercase (): undefined;}}    

Thus, 1.9.0 does not recommend the use of attr () to manipulate properties with a true and false two property.

So our conclusion is:

Properties with True and false two properties, such as checked, selected or disabled use prop (), and others using attr (), as shown in the following table:

Note: Most of the views and examples in this article are personal understanding, inevitably there are inaccurate places, welcomed the relevant research counterparts.

Differences between attr () and prop () methods in JQuery < goto >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.