jQuery

#Instance; event; performance; mobile; foundation

data

英[ˈdeɪtə] 美[ ˈdetə, ˈdætə, ˈdɑtə]

n. Data, material; plural of datum; [computer] data, information; value extracted from scientific experiments

jquery jQuery.data() method syntax

Function: data() method appends data to the selected element, or obtains data from the selected element. This is a low-level method; using .data() is more convenient.

Return function from element: Return additional data from the selected element.

Syntax: $(selector).data(name)

Parameters:

ParametersDescription
nameOptional. Specifies the name of the data to be retrieved. If no name is specified, this method returns all stored data from the element as an object.

#Append data to the element: Append data to the selected element.

Syntax: $(selector).data(name,value)

##Parameters:

ParametersDescriptionname Required. Specifies the name of the data to be set. value Required. Specifies the value of the data to be set.

#Use objects to append data to elements: Use objects with name/value pairs to add data to selected elements.

Syntax: $(selector).data(object)

Parameters:

ParameterDescriptionobject Required. Specifies an object containing name/value pairs.​

jquery jQuery.data() method example

<html>
<head>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#btn1").click(function(){
    $("div").data("greeting", "Hello World");
  });
  $("#btn2").click(function(){
    alert($("div").data("greeting"));
  });
});
</script>
</head>
<body>
<button id="btn1">把数据添加到 div 元素</button><br />
<button id="btn2">获取已添加到 div 元素的数据</button>
<div></div>
</body>
</html>
Run instance »

Click the "Run instance" button to view the online instance