Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

Jquery data()方法

data()方法用于附加和从所选元素获取数据。它是 JQuery 中的内置方法。我们可以使用 removeData()方法删除数据。

语法

该方法的常用语法为如下。下面有两种语法,其中第一种语法用于从选定元素返回数据,第二种语法用于将数据附加到选定元素。
返回数据
$(selector).data(name)
上述语法中的 name 是可选参数。它是检索数据的数据名称。如果未指定, data()方法会将元素的所有存储数据作为对象返回。此语法返回所选元素的检索数据。
附加数据
$(selector).data(name, value)
此语法用于将数据附加到选定的元素。上面语法中的参数 name value 是必选参数。名称指定要设置的数据 name ,值指定要设置的数据 value
现在,让我们看一个使用 data()方法了解如何返回数据并将数据附加到选定元素的示例。

示例

在此示例中,我们将数据附加到div元素。在这里,有两个按钮分别名为 附加数据获取数据附加数据按钮将数据附加到div元素,然后单击 获取数据按钮,将检索div元素的数据。
如果在单击 附加数据按钮之前单击 获取数据按钮,则会得到 未定义。因此,要查看附件中的数据,我们必须在点击 附加数据按钮后单击 获取数据按钮。
<html>
<head>
<title> jQuery data() method </title>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<style>
div {
padding: 10px;
background-color: lightblue;
font-size: 25px;
width: 350px;
}
</style>
</head>
<body>
<h4> This is an example of using the jQuery data() method. </h4>
<div> This is a div element. </div>
<p> Click the following buttons to see the effect. </p>
<button id = "b1"> 附加数据 </button>
<button id = "b2"> 获取数据 </button>
<script>
$("document").ready(function(){
$("#b1").click(function(){
$("div").data("name", "Welcome to the lidihuo.com");
alert("Data attached");
})
$("#b2").click(function(){
alert($("div").data("name"));
$("div").text($("div").data("name"));
})
});
</script>
</body>
</html>
输出:

This is an example of using the jQuery data() method.

This is a div element.

Click the following buttons to see the effect.

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4