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