The difference between the prop () method and the attr () method in jquery

Source: Internet
Author: User

Recently, when using jquery, there is a problem, that is the attr () method, found that the method sometimes used there are some problems that can not explain why. Before turning over your notes, there is a function prop ().

Both of these functions can be used to get properties.

jquery1.6 added a new method prop (), the official explanation is only one sentence: Gets the property value of the first element in the matching element set.

We all know that some browsers just write disabled,checked can be, and some to write disabled = "disabled", checked= "checked", such as with attr ("checked") The Checked property of the checkbox can be obtained when the value is selected, the value is "checked", but the get value is undefined.

JQ provides a new method of "prop" to get these properties, which is to solve this problem, we used attr to get the checked property when we return "checked" and "", and now use the Prop method to get the property is unified return True and false.

So, when to use attr (), when to use Prop ()?
1. Add property name This property will take effect should use Prop ();
2. There are true,false two attributes using prop ();
3. The other uses attr ();

The following are the official recommendations for the use of attr (), prop ():

Attribute/property .attr() .prop()
AccessKey
Align
Async
Autofocus
Checked
Class
Contenteditable
Draggable
Href
Id
Label
Location (i.e. window.location)
Multiple
ReadOnly
Rel
Selected
Src
TabIndex
Title
Type
Width (if needed over .width() )

The difference between the prop () method and the attr () method in jquery

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.