The data () method in jquery attaches to the selected element or gets the data from the selected element. This makes it very convenient to manipulate the data through HTML custom attributes. Often we also store and manipulate data by giving HTML custom attributes. And in jquery, give us
Provides a method of data (Name,value), which is very convenient to implement. With the data () method, you can easily add custom attributes such as data-* to an HTML tag. Next, take a simple look at the data () method.
The following is a description of data usage from W3school:
the data method reads the syntax from the element:
$ (selector). Data (name) name: Optional. Specifies the name of the data to retrieve.If no name is specified, the method returns all stored data from the element in the form of an object.
The data method stores the syntax from the element:
$ (selector). Data (name,value) name: Required. Specifies the name of the data to be set. Value: Required. Specifies the value of the data to be set.
Of course, here we can also add a data to the selected element with an object containing a key/value pair. The syntax is as follows:
$ (selector). Data (object) object: Required. Specifies an object that contains a name/value pair.
The HTML code is as follows:
the data method reads :
<div id= "Divname" data-name= "Lichaoqiang" > Single data: Data-name= "Lichaoqiang" </div> <div id= "Divjson" Data-user= ' {"user_id": 20141111, "user_name": "Lichaoqiang"} ' > Store JSON data: {"user_id": 20141111, "user_name": " Lichaoqiang "}</div> <script type=" Text/javascript "> console.log ($ (" #divName "). Data (" name ")) ; Output a single data Console.log ($ ("#divJson") by name. Data ("user"). user_name);//output JSON data by name
Note: When you set the JSON data in the element data-* attribute, you need to be aware of the single double quotes, otherwise the undefined may occur and the data cannot be obtained. The correct approach is to use double quotes.
data stored in the method :
<div id= "Container" > This is a div tag </div> <script type= "Text/javascript" > $ ("#container"). Data (" Name "," Lichaoqiang ");//Store Data Console.log ($ (" #container "). Data (" name "));//read from name </script>
Hope the above introduction, can help everyone!
Example of usage of data function in jquery