search
HomeWeb Front-endJS TutorialRead jQuery Part 6: Introduction to cache data function_jquery

Many students like to store data in HTMLElement attributes in projects, such as

Copy code The code is as follows:

Test

<script> <BR>div.getAttribute('data'); // some data <BR></script>> ;

Add custom attribute "data" and value "some data" to the div on the page. Use getAttribute to obtain it in subsequent JS code.
jQuery has provided the data/removeData method since 1.2.3 to store/delete data. 1.6.1 Code snippet
Copy code The code is as follows:

jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
...
});

adds a static field to jQuery /Methods, including jQuery.cache/jQuery.uuid/jQuery.expando, etc. The following introduces the
jQuery.cache empty object, used for caching. Its structure is more complex.
jQuery.uuid increments a unique number.
jQuery.expando string, generated using Math.random, with non-numeric characters removed. It serves as the property name of an HTMLElement or JS object.
Copy code The code is as follows:

expando: "jQuery" ( jQuery.fn.jquery Math .random() ).replace( /D/g, "" ),

jQuery.noData JS object, disables the data method for the specified HTMLElement. Such as embed, applet.
jQuery.hasData is used to determine whether the HTMLElement or JS object has data. Return true or false. That is, if the jQuery.data method is called to add attributes, it returns true.
Copy code The code is as follows:

aa

<script> <BR>var div = document.getElementsByTagName('div')[0]; <BR>$.hasData(div); // false <BR>$.data(div, 'name','jack '); <BR>$.hasData(div); // true <BR></script>

jQuery.acceptData is used to determine whether the element can accept data, returning true or false . Used in jQuery.data.
jQuery.data This is a method provided to client programmers. It is also a setter/getter.
1, pass one parameter, return all the data attached to the specified element, that is, thisCache jQuery.data(el); // thisCache
2, pass two parameters, return the specified attribute value jQuery.data(el, 'name');
3, pass three parameters, set attributes and attribute values ​​jQuery.data(el, 'name', 'jack');jQuery.data(el, 'uu', {});
4, pass four parameters, the fourth parameter pvt is only provided to the jQuery library itself. That is, pass true in the jQuery._data method. Because jQuery's event module relies heavily on jQuery.data, it was added in this version to avoid accidental rewriting.
jQuery.removeData deletes data.
The above is an overall overview of the jQuery data caching module. The following is a detailed description of the jQuery.data method. jQuery.data provides caching for two types of objects: JS objects and HTMLElement
Copy code The code is as follows:

// Provide cache for JS objects
var myObj = {};
$.data(myObj, 'name', 'jack');
$.data(myObj, 'name'); // jack
// Provide cache for HTMLElement

<script> <BR>var el = document.getElementById('xx' ); <BR>$.data(el, 'name', 'jack'); <BR>$.data(el, 'name'); // jack <BR></script>

There are also differences in the internal implementation.
1. When providing cache for JS objects, the data is saved directly on the JS object. cache is a JS object. At this time, an attribute will be secretly added to the JS object (similar to jQuery16101803968874529044), and the attribute value is also a JS object. For example
Copy code The code is as follows:

var myObj = {};
$ .data(myObj, 'name', 'jack');
console.log(myObj);

The structure of myObj is as follows
Copy code The code is as follows:

myObj = {
jQuery16101803968874529044 : {
name : 'jack'
}
}

The string "jQuery16101803968874529044" is named id inside data (note that it is not the id of the HTMLElement element). It is actually jQuery.expando. As mentioned above, it is randomly generated after jQuery.js is introduced to the page.
2. When caching is provided for HTMLElement, it will not be directly saved on HTMLElement. Instead it is saved on jQuery.cache. The cache is jQuery.cache. At this time, first add attributes to HTMLElement (similar to jQuery16101803968874529044), and the attribute values ​​​​are numbers (1, 2, 3 increase). That is, only some numbers are saved on the HTMLElement, and the data is not directly inserted. This is because there may be a risk of memory leaks in older versions of IE. And how does HTMLElement connect with jQuery.cache? Or ID. I just mentioned that the attribute value number is the id. For example
Copy code The code is as follows:


<script> <BR>var el = document.getElementById('xx'); <BR>$.data(el, 'name', 'jack'); <BR>console. log(el[jQuery.expando]); // 1 <BR>console.log(jQuery.cache); // {1 : {name:'jack'}} <BR></script>

el is added with the attribute jQuery.expando, the value is id, and this id is incremented from 1. The id is used as the attribute (key) of jQuery.cache. In this way, HTMLElement is connected to jQuery.cache. As shown in the picture

Read jQuery Part 6: Introduction to cache data function_jquery

Have you noticed that jQuery.data also has a fourth parameter pvt, which is only used in jQuery._data.

Copy code The code is as follows:

// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},

jQuery._data specifies from the naming that it is Private, client programmers using jQuery should not call this method. jQuery's API documentation doesn't expose it either.
jQuery’s data caching module changes in almost every version from 1.2.3 to 1.6.1. jQuery._data was proposed to prevent client programmers from overwriting/rewriting the default module. For example, the event handler in the jQuery event module is stored using jQuery.data, if the module is rewritten. Then the event module will be paralyzed. Therefore, the pvt parameter and jQuery._data method were specially added.
But if you deliberately want to destroy it, you can still do it. As follows
Copy the code The code is as follows:

Test< ;/div>
<script> <BR>$('#xx').click(function(){ <BR>alert('click'); <BR>}); <BR>// statement 1 <BR>$.data($('#xx')[0], 'events', '', true); <BR>// Statement 2 <BR>//$._data($('#xx ')[0], 'events', ''); <BR></script>

Clicking on div[id=xx] will not trigger the click event.
The entire jQuery.data setting (set) data cache process is like this, understand this. The process of getting data is easy to understand. Not repeated.
Finally, I will add the zChain.data/removeData method to zChian.js, because it is a "mini version" and only adds data caching to HTMLElement. Please note.

Related:
http://msdn.microsoft.com/en-us/library/Bb250448
http://bugs.jquery.com/ticket/6807
zChain-0.6.js

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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools