[difference between attr and prop methods in Js]jquery __javascript zone

Source: Internet
Author: User

Compared to the Attr,prop is 1.6.1 new, both from the Chinese meaning of understanding, are to get/set properties of the method (attributes and properties). Only the. attr () method used in window or document does not work well before jQuery1.6 because attributes is not available in window and document. Prop was born.

Before looking at the online comparison between the two articles, but also lists a table to distinguish what labels under the use of prop, what labels under the use of attr, forgive me is lazy people, the most afraid to back things, so only their own to think of ways.

Since we want to know the difference between them, it is best to look at their source code, not to be frightened by the length of the code, we only look at the key words:

attr Method Code (jquery version 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 &&A mp Jquery.isfunction (jquery.fn[name]) {return jQuery (elem) [name] (value);}//fallback to prop when attributes a Re not supported if (typeof Elem.getattribute = = "undefined") {return Jquery.prop (elem, name, value);} notxml = Nty PE!== 1 | | !jquery.isxmldoc (Elem); All attributes are lowercase//Grab necessary hooks 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 &&am P "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) {RE Turn ret; else {ret = Elem.getattribute (name);

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.