Home >Web Front-end >JS Tutorial >Detailed explanation of the use of prop() attr() in jQuery_jquery

Detailed explanation of the use of prop() attr() in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 15:58:221199browse

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.

Copy code The code is as follows:

http://www.baidu.com" target="_self" class="btn">Baidu

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.

Copy code The code is as follows:

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:

Copy code The code is as follows:

Is it visible
Is it visible

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.

Copy code The code is as follows:

$("#chk1").prop("checked") == false
$("#chk2").prop("checked") == true

If the attr method is used above, it will appear:

Copy code The code is as follows:

$("#chk1").attr("checked") == undefined
$("#chk2").attr("checked") == "checked"

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn