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.com/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.