Home >Web Front-end >JS Tutorial >jQuery data cache usage analysis_jquery

jQuery data cache usage analysis_jquery

WBOY
WBOYOriginal
2016-05-16 16:13:23944browse

This article analyzes jQuery data caching usage. Share it with everyone for your reference. The details are as follows:

In jQuery’s API help documentation, jQuery describes the role of data caching as follows: used to access data on an element without the risk of circular references.

1. Define cache data

Use the $(selector).data(name,value) method to define cached data for jQuery objects. These cached data are stored in all DOM elements in the matching DOM element set.

var $link = $('a');
$link.data('linkType', 'home');

Note: $(selector).data(name,value) can store data in any format on the matching DOM element, not just strings.

2. Obtain cache data

At this point, only one parameter is needed, which specifies the name of the cached data.

var linkType = $link.data('linkType'); //'home'

Note: If the read cache data does not exist, the return value is undefined; if the jQuery collection points to multiple elements, only the corresponding cache data of the first element will be returned.

3. Delete cached data

The removeData() function can delete cached data with a specified name and return the corresponding jQuery object.

//删除缓存数据的同时,返回对应的jQuery对象。
var $a = $link.removeData('linkType');  

4. Specifications for using jQuery data cache

As the number of times the data() function is called increases, or due to improper use, the cache object will expand rapidly, ultimately affecting the performance of the program.
Therefore, when using the jQuery data caching function, the cache objects should be cleared in time. jQuery provides the removeData() function to manually clear cached data. According to the operating mechanism of the jQuery framework, there is no need to manually clear the data cache in the following situations.

* Perform the remove() operation on elem, and jQuery will automatically clear the cache that may exist on the object.
* Perform the empty() operation on elem. If there is a data cache for the current elem sub-element, jQuery will also know the possible data cache for the sub-object.
* The clone() method of jQuery copying nodes will not copy the data cache.

I hope this article will be helpful to everyone’s jQuery programming.

Statement:
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