$.attr() and $.data() essentially belong to the difference between DOM attributes and Jquery object attributes. The following is an example to introduce to you the difference between .attr() and .data() in jQuery. Let’s take a look.
$.attr() and $.data() essentially belong to DOM attributes and Jquery objects. attribute differences.
Jquery object attributes and DOM attributes
A simple example
• $.attr() takes the value of the attribute from the DOM element every time, that is, and the view The attribute values in the tags remain consistent. •$.attr('data-foo') will get the data-foo attribute value from the tag;
•$.attr('data-foo', 'world') will get the string 'world' is stuffed into the 'data-foo' attribute of the tag;
•$.data() takes the value from the Jquery object. Since the object attribute value is stored in memory, it may be different from the value in the view. Inconsistent attribute values. •$.data('foo') will get the attribute value of foo from the Jquery object, not the data-foo attribute value from the tag;
•$.data('foo', ' world') will stuff the string 'world' into the 'foo' attribute of the Jquery object instead of the data-foo attribute of the view tag.
Combining the above code and explanation, everyone should be able to understand the difference between the two.
Summary
So $.attr() and $.data() should avoid mixed use, that is, the following two situations should be avoided as much as possible:
1. Use $.attr() to set the attribute, and then use $.data() to get the attribute value;
2. Use $.data() to set the attribute, and then use $.attr() get attribute value.
At the same time, from a performance perspective, it is recommended to 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.
Related recommendations:
The difference between jQuery’s attr() and prop()
jQuery: The difference between attr() and prop()
The above is the detailed content of The difference between .attr() and .data() in jQuery. For more information, please follow other related articles on the PHP Chinese website!