The difference between .attr() and .data() in jQuery

小云云
Release: 2017-12-29 11:20:35
Original
1232 people have browsed it

$.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

    Jquery中.attr和.data的区别 
  

Copy after login

• $.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()

CSS attribute attr()

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!