When should I use prop after the prop method is introduced in the advanced version of jquery? When to use attr? Let's talk about the differences between them. My experience is simple: the inherent attributes of HTML elements are used in the prop method. For DOM attributes customized by HTML elements, the attr method is used for processing. For the inherent attributes of HTML elements, the prop method is used for processing.
For DOM attributes customized by HTML elements, the attr method is used for processing.
When should I use prop after the prop method is introduced in the advanced version of jquery? When to use attr? What is the difference between them? These problems occur.
There are many answers to the differences between them on the Internet. Here is my experience. My experience is very simple:
For the inherent attributes of HTML elements, the prop method is used for processing.
For DOM attributes customized by HTML elements, the attr method is used for processing.
The above description may be a bit vague. Let's take a few examples.
The Code is as follows:
Http://www.baidu.com "target =" _ self "class =" btn "> Baidu
In this example, the DOM attributes of an element include "href, target, and class". These attributes are attributes contained in the element itself, which are also included in the W3C standard, or the attributes that can be intelligently displayed in the IDE are called inherent attributes. When processing these attributes, we recommend that you use the prop method.
The Code is as follows:
Delete
In this example, the DOM attributes of an element include "href, id, and action". Obviously, the first two attributes are inherent, And the next "action" attribute is customized by ourselves, the element itself does not have this attribute. This is the custom DOM attribute. We recommend that you use the attr method when processing these attributes. When the prop method is used to set values and attribute values, the undefined value is returned.
Another example:
The Code is as follows:
Visible or not
Visible or not
Elements such as checkbox, radio, and select correspond to "checked" and "selected". These are also inherent attributes. Therefore, you must use the prop method to obtain the correct results.
The Code is as follows:
$ ("# Chk1"). prop ("checked") = false
$ ("# Chk2"). prop ("checked") = true
If the attr method is used above, the following error occurs:
The Code is as follows:
$ ("# Chk1"). attr ("checked") = undefined
$ ("# Chk2"). attr ("checked") = "checked"
The above is all the content of this article. I hope you will like it.