How to use jquery data()

青灯夜游
Release: 2022-03-03 15:53:57
Original
2770 people have browsed it

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)
Copy after login
ParametersDescription
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)
Copy after login
ParametersDescription
nameRequired. Specifies the name of the data to be set.
valueRequired. 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)
Copy after login
ParametersDescription
objectRequired . 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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template