Getting started with jQuery: Data method, jquery getting started with data

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.