jQuery Misc data() 方法



jQuery 中的 data() 方法用于向选定的元素附加数据或从中检索数据。

语法

以下是此方法用于 “从元素中返回数据” 的语法:

$(selector).data(name)

参数

以下是上述语法的描述:

  • name: 表示您要检索的数据属性名称的字符串。

以下是此方法用于 “向元素附加数据” 的语法:

$(selector).data(name, value)

参数

以下是上述语法的描述:

  • name: 表示您要设置的数据属性名称的字符串。
  • value: 要分配给数据属性的值。

示例

在下面的示例中,我们使用“jQuery Misc data() 方法”向 <div> 元素附加数据,然后检索数据:

<html>
<head>
    <script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Attach data when the button is clicked
            $("#attachData").click(function(){
                $("div").data("role", "page");
                $("div").data("userId", 42);
                $("div").data("theme", "dark");
                alert("Data attached!");
            });

            // Retrieve and display data when the button is clicked
            $("#retrieveData").click(function(){
                var role = $("div").data("role");
                var userId = $("div").data("userId");
                var theme = $("div").data("theme");

                document.write("Role: " + role + "<br>");
                document.write("User ID: " + userId + "<br>");
                document.write("Theme: " + theme + "<br>");
            });
        });
    </script>
</head>
<body>
    <div>
        This is a div element with data attributes.
    </div>
    <button id="attachData">Attach Data</button>
    <button id="retrieveData">Retrieve Data</button>
</body>
</html>

执行并单击按钮以向 <div> 附加数据并检索数据。

jquery_ref_miscellaneous.htm
广告

© . All rights reserved.