HTML data-* 属性 自定义属性

data-* 属性用于存储私有页面后应用的自定义数据。

data-* 属性可以在所有的 HTML 元素中嵌入数据。

自定义的数据可以让页面拥有更好的交互体验(不需要使用 Ajax 或去服务端查询数据)。

data-* 属性由以下两部分组成:

  1. 属性名不要包含大写字母,在 data- 后必须至少有一个字符。

  2. 该属性可以是任何字符串

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <title></title>
</head>
<body>
    <div id="testDiv" data-cname="张三" data-e-name="zhangsan" data-user-id="123456">111111111</div>

    <div id="test" data-age="24">Click Here</div>

    <div id="example" data-info="hello">这是一个示例</div>

    <div id="example2" data-custom-attribute="value">这是一个示例example2</div>
    <br />
    <div>
        <input id='chkTest' type="checkbox" data-fun-description="同意" />同意协议
        <input id="saveBtn" type="button" value="保存" />
    </div>
    <script type="text/javascript">
        $(document).ready(function () {
            //JavaScript
            var userId = document.querySelector('div').dataset.userId;
            console.log("Ln 25:" + userId);   // 输出: 123456

            var usercname = document.getElementById('testDiv').getAttribute('data-cname');
            console.log("Ln 28:" + usercname); // 输出: 张三

            var el = document.getElementById("testDiv");
            console.log("Ln 31:" + el.dataset.cname);//输出: 张三
            el.dataset.cname = "ZS";//设置值为"ZS"
            console.log("Ln 33:" + el.dataset.cname);//输出: ZS

            //jQuery
            var info = $('#example').data('info');
            console.log("Ln 37:" + info);     // 输出: hello

            var infoAttr = $('#example').attr('data-info');// 直接获取原始字符串值
            console.log("Ln 40:" + infoAttr); // 输出: hello

            $('#example').data('info', 'world');
            var updatedInfo = $('#example').data('info');
            console.log("Ln 44 修改内容:" + updatedInfo); // 输出: world

            var value = $('#example2').data('customAttribute'); // 注意:驼峰命名法转换规则(camelCase)
            console.log("Ln 47:" + value); // 输出:value


            $('#example').data('customAttribute', 'newValue'); // 设置值
            var updatedValue = $('#example').data('customAttribute'); // 读取值
            console.log("Ln 52 修改内容:" + updatedValue); // 输出:newValue

            //复选框 prop 选中状态
            $('#saveBtn').click(function () {
                if ($('input[type="checkbox"]:checked[data-fun-description="同意"]').prop('checked')) {
                    console.log("Ln 57:选中");
                } else {
                    console.log("Ln 57:未选中");
                }
            });

            console.log("Ln 63 删除testDiv元素上 ename 键/值对。");
            $("#testDiv").removeData("ename");
        });
    </script>
</body>
</html>

*

*

*

*

*