Home  >  Article  >  Web Front-end  >  How to use jquery data()

How to use jquery data()

青灯夜游
青灯夜游Original
2022-03-03 15:53:572766browse

In jquery, the data() method can be used to append data to selected elements, the syntax is "$(selector).data(name,value)"; it can also be used to obtain data from selected elements. , syntax "$(selector).data(name)".

How to use jquery data()

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

jquery data() method

data() method appends data to the selected element, or obtains data from the selected element.

Syntax:

  • Return additional data from the selected element.

$(selector).data(name)
Parameters Description
name

Optional. Specifies the name of the data to be retrieved.

If no name is specified, this method will return all stored data from the element in the form of an object.

  • Append data to the selected element.

Can be a single name/value pair

$(selector).data(name,value)
Parameters Description
name Required. Specifies the name of the data to be set.
value Required. Specifies the value of the data to be set.

You can also use objects with name/value pairs to add data to selected elements.

$(selector).data(object)
Parameters Description
object Required . Specifies an object containing name/value pairs.

Example: Append data to an element and then retrieve that data

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.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>

How to use jquery data()

##【 Recommended learning:

jQuery video tutorial, web front-end

The above is the detailed content of How to use jquery data(). For more information, please follow other related articles on the PHP Chinese website!

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