This article mainly introduces the usage of $. data in jQuery's data cache and complete source code parsing. It provides an in-depth explanation of jQuery's implementation of reading, writing, and removing cached objects. For more information, see
I. Implementation principle:
For a DOM element, assign a unique association id to associate the DOM element with the data cache object of the DOM element. The association id is appended to jQuery. the data is stored in the global cache object jQuery. cache. When reading, setting, and removing data, the global cache object jQuery. find the associated data cache object in the cache, and then perform the read, set, and remove operations on the data cache object.
For Javascript objects, the data is directly stored on jQuery. expando, the property of the Javascript Object. When reading, setting, and removing data, it actually reads, sets, and removes the data cache objects of Javascript objects.
To avoid conflicts between the data used inside jQuery and user-defined data, the data cache module stores the internal data on the data cache object, store custom data on the property data of the data Cache object.
Ii. Overall Structure:
// Data cache DatajQuery. extend ({// global cache object cache :{}, // unique id seed uuid: 0, // expando: "jQuery" + (jQuery. fn. jquery + Math. random ()). replace (/\ D/g, ""), // whether associated data hasData: function () {}, // set, read custom data or internal data: function (elem, name, data, pvt) {}, // remove custom data or internal data removeData: function (elem, name, pvt ){}, // set and read internal data _ data: function (elem, name, data) {}, // can you set data acceptData: function (elem) {}}); jQuery. fn. extend ({// set and read custom data, parse HTML5 attribute data-data: function (key, value) {}, // remove Custom data removeData: function (key) {}}); // parse the HTML5 attribute data-function dataAttr (elem, key, data) {}// check whether the data cache object is empty function isEmptyDataObject (obj) {} jQuery. extend ({// clear the data cache object cleanData: function (elems ){}});
Iii. $. data (elem, name, data), $. data (elem, name)
$. Data (elem, name, data) usage:
If name or data is input, data of any type is set.
JQuery. data demo