Comparison between attr () and prop () methods in jQuery

Source: Internet
Author: User
Tags lowercase

I have been using jQuery 1.8.3 and have never tried jQuery 1.9.0.

Then, start debugging the code in version 1.9.0:

The code is as follows: Copy code
<Input type = "checkbox"/> <script >$ (function (){
$ ('Input'). click (function (){
$ (This). attr ('checked ');
});
}); </Script>

Click checkbox and the result is undefined.

In version 1.8.3, the results are checked and undefined.

At this point, the answer to the question is the question of using the attr () method. So I checked the official documentation and found that a method prop () was added since jQuery 1.6 (), but it has never been used.

From the Chinese meaning, the two are respectively the methods for obtaining/setting attributes and properties. Why do we need to add the prop () method?

Before jQuery 1.6, the. attr () method sometimes took property values into account when retrieving some attributes, which cocould cause inconsistent behavior.
Because before jQuery 1.6, using attr () may sometimes lead to inconsistencies.

So when will attr () and prop () be used ()?

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the. prop () method.
According to official recommendations: attributes with true and false attributes, such as checked, selected, or disabled, use prop (), and others use attr ()

At this point, change attr ('checked') to prop ('checked') to fix the proposed issues.

Pai_^

Wait, it seems that the problem has not been solved. Why is the difference between jQuery 1.8.3 and 1.9.0 using attr () in the first example?

The best way to know their differences is to look at their source code:

1.8.3 attr ():

The code is as follows: Copy code

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 ():

The code is as follows: Copy code

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

The prop () of 1.8.3 and 1.9.0 is the same:

The code is as follows: Copy code

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

First, let's take a look at the differences between attr () and prop:

The two most critical lines of code in attr ()

The code is as follows: Copy code

Elem. setAttribute (name, value + "");

Ret = elem. getAttribute (name );

Obviously, the dom api setAttribute () and getAttribute () methods are used to operate attribute element nodes.

Two key lines of code in prop ()

The code is as follows: Copy code
Return (elem [name] = value); return elem [name];

It can be understood as document. getElementById (el) [name] = value, which is an attribute converted to element.

Compare the attr () methods of 1.9.0 and 1.8.3, and find that the difference between the two is:

Hooks. get (elem, name ))
The returned values are different. Specific implementation:

In 1.8.3

The code is as follows: Copy code

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

We can see that attr () is not recommended for operations on attributes with the true and false attributes starting from 1.9.0.

So our conclusion is:

Attributes with true and false attributes, such as checked, selected, or disabled, use prop (), and others use attr (). For details, see the following table:

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.