Jquery method of adding attribute values to elements: 1. Use the "$(element)" statement to obtain the specified element object; 2. Use the attr() method to add attributes and values to the obtained element. The syntax is: "Element object.attr(attribute,value)".
The operating environment of this tutorial: windows7 system, jquery1.10.0 version, Dell G3 computer.
How to add attribute values to elements in jquery
In jQuery, you can use the attr() method to add attribute values to elements, attr() Method sets or returns the attribute value of the selected element. Depending on the parameters of the method, the way it works is also different. Returns the attribute value of the selected element.
The syntax of this method is:
$(selector).attr(attribute,value)
attribute specifies the attribute whose value is to be obtained.
Let's take an example to see how to add attribute values to elements. The example is as follows:
We add a div in html, which only has the class attribute. Then add a button to trigger the event of adding attributes. Then introduce jquery script into html. Then add a function in the script, the function of the button event.
The function is very simple. Just use jquery's attr method to set the attribute. The first parameter is the name of the attribute to be added, and the second parameter is the value of the attribute. Here we add an id attribute to the div.
<body> <div class=""> <div class="jqyery"> 增加属性 </div> </div> <div class="action"> <input type="button" id="btn" value="设置属性" onlick="setAttr()" class="btn btn-primary" /> </div> <scripr> function setAttr(){ $(".jquery").attr("id","bd"); } </scripr> </body>
After running the page, from the page source code, this div now has no id attribute.
Click the button on the page to trigger the event and add the id attribute to the div.
After clicking, look at the source code again, and you can see that an id attribute has been successfully added to the div.
Recommended related video tutorials: jQuery video tutorial
The above is the detailed content of How to add attribute value to element in jquery. For more information, please follow other related articles on the PHP Chinese website!