For the inherent attributes of the HTML element itself, use the prop method when processing.
For our own custom DOM attributes of HTML elements, we use the attr method when processing them.
After the prop method is introduced in higher versions of jquery, when should prop be used? When to use attr? What's the difference between the two of them? These problems arise.
There are many answers online about the difference between the two. Let me talk about my thoughts here. My thoughts are very simple:
For the inherent attributes of the HTML element itself, use the prop method when processing.
For our own custom DOM attributes of HTML elements, we use the attr method when processing them.
The above description may be a bit vague, just give a few examples.
In this example, the DOM attributes of the element include "href, target and class". These attributes are the attributes of the element itself. These attributes are also included in the W3C standard, or can be intelligently prompted in the IDE. The attributes that appear are called intrinsic attributes. When dealing with these properties, it is recommended to use the prop method.
In this example, the DOM attributes of the element include "href, id and action". Obviously, the first two are inherent attributes, while the latter "action" attribute is customized by us. The element itself does not have this attribute. of. This is a custom DOM attribute. When dealing with these attributes, it is recommended to use the attr method. When using the prop method to get values and set property values, undefined values will be returned.
Another example:
For elements like checkbox, radio and select, the checked attributes correspond to "checked" and "selected". These are also inherent attributes, so you need to use the prop method to operate to get the correct result.
If the attr method is used above, it will appear:
The above is the entire content of this article, I hope you all like it.