In jquery, the full name of attr is "attribute", which means "attribute". It is an attribute operation method that can return the attribute value of the element. The syntax is "element.attr("attribute name")"; also One or more attribute/value pairs can be set for an element, with the syntax "element.attr({attribute:value, attribute:value...})".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
In jquery, the full name of attr is "attribute", which means "attribute" in Chinese.
attr() is an attribute operation method in jquery that can set or return the attributes 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.
When this method is used to set attribute values, one or more attribute/value pairs are set for the matching element.
Syntax:
Return the value of the attribute:
$(selector).attr("属性名")
Set attributes and values:
//设置单个属性和值: $(selector).attr("属性","值") //设置多个属性和值: $(selector).attr({属性:值,属性:值,...})
Example 1: Return attribute value
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { alert("图片宽度: " + $("img").attr("width")); }); }); </script> </head> <body> <img src="img/1.jpg" alt="Pulpit Rock" width="284" style="max-width:90%"> <br> <button>返回图片的宽度</button> </body> </html>
Example 2: Set the width attribute of the image
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("img").attr("width","500"); }); }); </script> </head> <body> <img src="img/1.jpg" alt="Pulpit Rock" width="284" style="max-width:90%"> <br> <button>为图片设置width属性</button> </body> </html>
Example 3: Setting multiple property and value pairs
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("img").attr({width:"150",height:"100"}); }); }); </script> </head> <body> <img src="img/1.jpg" alt="Pulpit Rock" width="284" style="max-width:90%"> <br> <button>给图片设置宽度和高度属性</button> </body> </html>
[Recommended learning: jQuery video tutorial 、web front-end video】
The above is the detailed content of What does attr mean in jquery. For more information, please follow other related articles on the PHP Chinese website!