The official examples are similar to attr () And I don't know what the difference is. Since the new prop () method is available, it cannot be used. When should I use attr (), when should I use prop ()? A method prop () has been added in jquery1.6 and has never been used. The official explanation is only one sentence: Get the attribute value of the first element in the matched element set.
We all know that some browsers only need to write disabled and checked, while some need to write disabled = "disabled", checked = "checked", such as attr ("checked ") you can obtain the value when you select the checked attribute of the checkbox. The value is "checked", but the undefined value is not selected.
Jq provides a new method "prop" to obtain these attributes to solve this problem. In the past, when we used attr to obtain the checked attribute, we returned "checked" and "", if you use the prop method to obtain attributes, both true and false are returned.
So when will attr () and prop () be used ()?
1. Add a property name. This property will take effect. Use prop ();
2. There are true and false attributes using prop ();
3. For others, use attr ();
Pay attention to this when upgrading jquery in the project!
We recommend that you use attr () and prop () as follows:
| 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()) |
√ |
|