Home > Article > Web Front-end > How to add an attribute and value in jquery
Two methods: 1. Use attr() to add, the syntax is "element object.attr("attribute name","value")" or "element object.attr({attribute:value})"; 2. Use prop() to add, the syntax is "element object.prop("property","value")" or "element object.prop({property:value})".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
There are two ways to add attributes and values to elements in jquery:
Use attr()
Use prop()
The prop() method and the attr() method are both used to get or set the HTML attributes of the element, and the syntax is similar.
1. Use attr()
Syntax for adding an attribute and value:
元素对象.attr("属性名","值") 元素对象.attr({属性:值})
Example: Add the disabled attribute to the text box and set it to be non-editable
<!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() { $("textarea").attr("disabled", "disabled"); // $("textarea").attr({disabled:true}); }); }); </script> </head> <body> <textarea></textarea><br><br> <button>让textarea不可编辑</button> </body> </html>
2. Use prop()
Syntax to add an attribute and value:
元素对象.prop("属性","值") 元素对象.prop({属性:值})
Example : Add the readonly attribute to the input box and set it to be read-only
<!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() { $("input").prop("readonly","readonly"); //$("input").prop({readonly:true}); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <input type="text" value="hello"/><br /><br /> <button>给input添加只读属性</button> </body> </html>
Description: The
prop() method is similar to the attr() method , but there are also essential differences. 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 other attributes are recommended to use the attr() method to operate.
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of How to add an attribute and value in jquery. For more information, please follow other related articles on the PHP Chinese website!