Home  >  Article  >  Web Front-end  >  A brief analysis of the difference between the prop() method and attr() method in jquery_Basic knowledge

A brief analysis of the difference between the prop() method and attr() method in jquery_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:23:221142browse

There is a new method prop() added in jquery 1.6. I have never used it. The official explanation is only one sentence: Get the attribute value of the first element in the matched element set.

Everyone knows that some browsers only need to write disabled and checked, while others need to write disabled = "disabled", checked="checked", such as when using attr("checked") to get the checked attribute of checkbox The value can be obtained when it is selected. The value is "checked" but the value obtained when it is not selected is undefined.

jq provides a new method "prop" to get these attributes to solve this problem. In the past, when we used attr to get the checked attribute, we returned "checked" and "". Now, when we use the prop method to get the attribute, we uniformly return true and false.

So, when to use attr() and when to use prop()?
1. Add the attribute name and the attribute will take effect. You should use prop();
2. If there are two attributes, true and false, use prop();
3. For other attributes, use attr();
Everyone should pay attention to this when upgrading jquery in the project!

The following are official recommendations for the use of attr() and 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() )  
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