Getting started with jQuery: Data method, jquery getting started with data
There are often situations where you want to store the data of an element. In Native JavaScript, you may do this by adding DOM element attributes, but you have to deal with some browser memory leaks. JQuery provides a direct way to store data related to an element, and it manages memory problems for you.
// Store and retrieve the data associated with the element $ ("# myDiv "). data ("keyName", {foo: "bar"}); $ ("# myDiv "). data ("keyName"); // Returns {foo: "bar "}
Any type of data may be stored in an element. The purpose of this article,.data()
It will be used to store references of other elements.
For example, you may want to create a list item and its internal<div>
. This association can be created independently each time it comes into contact with the list item. But a better solution is to create this association at one time and then use.data()
Store<div>
Pointer:
// Use. association between data () storage elements $ ("# myList li "). each (function () {var li = $ (this); var div = li. find ("div. content "); li. data ("contentDiv", div) ;}); // Later, we don't have to find the div again; // Later, you don't have to look for the div again; // we can just read it from the list item's data // we can read var firstLi =$ ("# myList li: first") through the data of the list item "); firstLi. data ("contentDiv" ).html ("new content ");
Besides passing.data()
You can also pass an object to include one or more key-value pairs.
Original article address