Home > Article > Web Front-end > What are the commonly used methods to obtain attributes in jquery?
The commonly used methods for obtaining attributes in jquery are: 1. attr() method, which can obtain and return the value of the specified attribute. The syntax is "$(selector).attr("attribute name")"; 2. prop( ) method, which can return the attribute value of the selected element, the syntax is "$(selector).prop("property name")".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
There are two commonly used methods for obtaining attributes in jquery:
attr() method
prop() method
jquery attr() method
attr() method sets or returns the attribute value of the selected element.
Example: Get the value of the width attribute of the img element
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { alert("图片宽度为 " + $("img").attr("width")); }); }); </script> </head> <body> <img src="img/1.jpg" style="max-width:90%" / alt="What are the commonly used methods to obtain attributes in jquery?" > <br /> <button>返回图像的宽度</button> </body> </html>
##jquery prop() method## The #prop() method sets or returns the properties and values of the selected element.
When this method is used to return an attribute value, the value of the first matching element is returned.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { alert("图片宽度为 " + $("img").prop("width")); }); }); </script> </head> <body> <img src="img/1.jpg" style="max-width:90%" / alt="What are the commonly used methods to obtain attributes in jquery?" > <br /> <button>返回图像的宽度</button> </body> </html>
prop() method and attr( ) methods are similar, both are used to get or set the HTML attributes of elements, but there are essential differences between the two.
jQuery official recommendation: For attributes with two values of true and false, such as checked, selected, disabled, etc., it is recommended to use the prop() method to operate, while for other attributes it is recommended to use the attr() method. to operate.
[Recommended learning:
jQuery video tutorialThe above is the detailed content of What are the commonly used methods to obtain attributes in jquery?. For more information, please follow other related articles on the PHP Chinese website!