This article will share about the difference between attr() and prop() in jQuery for setting attributes and getting attributes. It has certain reference value and I hope it will be helpful to everyone.
We often get used to it. Use the attr() method to get the attribute value. For example, if you want to get the alt attribute of an image, we can use attr to get it directly. However, in some elements, you cannot directly get the standard attribute (true/false), so we later got the prop attribute. , its return values are all standard attributes, so which attributes use attr and which use prop? We will introduce the
attr attribute in detail in the following article
attr(name|properties|key,value|fn)
is used Sets or returns the attribute value of the selected element.
When used to return attribute values, only the value of the first matching element is returned.
When used to set attribute values, one or more attribute/value pairs are set for the set of matching elements
Example: Set the src attribute and length and width for all images
<body> <img> <script src="jquery/jquery-1.12.4.js"></script> <script> $(function(){ $("img").attr({width:"100px",height:"100px","src":"images/1.jpg"}); })//为img添加多个属性值 </script> </body>
prop attribute
Get the attribute value of the first element in the matched element set
Selected is true, unselected is false
When selecting a hobby, select all, other single selections, when all four are selected, all hobbies are selected
<script src="jquery/jquery-1.12.4.js"></script> <script> $(function () { $("#j_cbAll").click(function () { //修改下面的哪些checkbox $("#j_tb input").prop("checked", $(this).prop("checked")); }); $("#j_tb input").click(function () { if($("#j_tb input:checked").length == $("#j_tb input").length){ $("#j_cbAll").prop("checked", true) }else { $("#j_cbAll").prop("checked", false) } }); }); </script>
When single selection
When choosing a hobby
The difference between attr and prop:
( 1) For example, in checked, selected, disabled, etc., the prop method returns a Boolean value, while attr returns a defined string
(2) The prop() attribute is used to set or get the specified DOM Elements are also object attributes in JavaScript, so we can set arrays or objects, and attr acts on document nodes, so it can only be strings
(3) The use of prop() attributes is more compatible than attr
So when the attribute only needs to add the attribute name, you can use attr, and when you only need to return true/false, you can use prop.
Summary: The above is the entire content of this article. I hope that through this article, everyone can understand the difference between attr and prop
The above is the detailed content of What is the difference between attr and prop in jQuery. For more information, please follow other related articles on the PHP Chinese website!