Home >Web Front-end >Front-end Q&A >Can jquery customize attributes?
jquery can customize attributes. In jquery, you can use attr() to add custom attributes to elements and set the attribute value; if you only add a single attribute, you can use "element object.attr("attribute name", "value")", if there are multiple attributes, use "Element object.attr({attribute name: value, attribute name: value,...})".
The operating environment of this tutorial: windows7 system, jquery3.2.1 version, Dell G3 computer.
jquery can customize attributes.
In jquery, there is a built-in method: attr(), which can customize attributes.
attr() method sets or returns the attribute and value of the selected element
When this method is used to return the 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.
This method can set built-in attributes or add custom attributes to the element.
If you are setting a single attribute, you can use the following syntax:
$(selector).attr("属性名","值")
If you are setting multiple attributes, you can use the following syntax:
$(selector).attr({属性名:值,属性名:值,...})
Example: Add custom attributes and output values
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="js/jquery-3.2.1.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").attr('myIndex',2); console.log($("div").attr('myIndex')); }); }); </script> </head> <body> <button>添加自定义属性</button> <div>hello</div> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of Can jquery customize attributes?. For more information, please follow other related articles on the PHP Chinese website!