jQuery data()的例子

jQuery data()的例子

data()是jQuery中的一个内置方法,用于附加数据或获取所选元素的数据。
语法:

$(selector).data(para1);

参数:它接受一个可选的参数 “para1″,指定为所选元素检索的数据名称。
返回值:它返回所选元素的检索数据。
jQuery代码显示data()方法的工作:
代码 #1:
在下面的代码中,数据被附加到选定的元素上。

<html>
 
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/
                 jquery/3.3.1/jquery.min.js"></script>
    <style>
        div {
            display: block;
            width: 500px;
            font-size: 37px;
            padding: 50px;
            background-color: lightgrey;
        }
         
        span {
            color: green;
        }
    </style>
</head>
 
<body>
    <div>
        Welcome to
        <span></span>for<span></span>!
    </div>
    <script>
        <!-- jQuery code to perform data method -->
        ("div").data("test", {
            first: "Geeks",
            last: "Geeks !"
        });
        ("span:first").text(("div").data("test").first);
        ("span:last").text($("div").data("test").last);
    </script>
</body>
 
</html>

输出:

jQuery data()的例子

代码 #2:
在下面的代码中,数据是使用按钮从 “div “元素中附加和获取的。

<html>
 
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/
                 jquery/3.3.1/jquery.min.js"></script>
    <script>
        (document).ready(function() {
        <!--Here data is attaching to the div element -->
            ("#b1").click(function() {
                ("div").data("g", "GeeksforGeeks !!!");
            });
        <!-- Here data is retrieving from the div element -->
            ("#b2").click(function() {
                alert($("div").data("g"));
            });
        });
    </script>
    <style>
        #b1,
        #b2 {
            padding: 10px;
            margin: 5px;
        }
    </style>
</head>
 
<body>
<!-- This button will attach data to the div element -->
    <button id="b1">This will attach data to div
                       element</button>
    <br>
<!-- This button retrieve the attached data
            from the div element -->
    <button id="b2">This will retrieve the attached data
                     to div element</button>
    <div></div>
</body>
 
</html>

输出:
就在点击运行按钮之后-

jQuery data()的例子

在点击 “这将检索附在div元素上的数据 “按钮之后,就在点击 “这将把数据附在div元素上 “按钮之后–

jQuery data()的例子

在点击 “这将检索附在div元素上的数据 “按钮后,没有点击 “这将把数据附在div元素上 “按钮–

jQuery data()的例子

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程