Differences between. attr () and. data () in jQuery
$. Attr () and $. data () are essentially the Differences Between DOM attributes and Jquery object attributes.
Jquery object attributes and DOM attributes
A simple example
<! DOCTYPE html>
• $. Attr () retrieves attribute values from the DOM element each time, that is, they are consistent with the attribute values in the labels in the view. • $. Attr ('data-foo') obtains the data-foo attribute value from the tag;
• $. Attr ('data-foo', 'World') inserts the 'World' string into the 'data-foo' attribute of the tag;
• $. Data () is a value from the Jquery object. Because the object property value is stored in the memory, it may be different from the attribute value in the view. • $. Data ('foo') obtains the foo attribute value from the Jquery object, instead of the data-foo attribute value from the label;
• $. Data ('foo', 'World') inserts the string 'World' into the 'foo' attribute of the Jquery object, rather than the data-foo attribute of the view tag.
Based on the above Code and explanations, you should be able to understand the differences between the two.
Summary
Therefore, $. attr () and $. data () should be used together to avoid the following two situations:
1. set attributes through $. attr () and get attribute values through $. data;
2. set attributes through $. data () and get attribute values through $. attr.
In terms of performance, we recommend that you use $. data () for set and get operations, because it only modifies the attribute value of the Jquey object and does not cause additional DOM operations.