HTML5 - 自定义属性

作者: Hyso | 来源:发表于2019-03-04 15:55 被阅读0次
    • HTML5中,自定义属性需以 data- 为前缀,如 data-name="Jack"。
    • HTML5中,可通过 dataset 对象获取自定义属性的值。
    • HTML5中,dataset 对象获取语法:
    document.querySelector("选择器").dataset
    
    获取自定义属性

    自定义属性获取语法:

    Element.dataset.属性名 或 Element.dataset['属性名']
    

    示例:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
    </head>
    <body>
    <div id="person" data-name="Petter" data-age="26" data-employee-number="001">车间员工</div>
    
    <script>
        var data = document.querySelector("#person").dataset;
        var name1 = data.name;
        var age1 = data.age;
        var employeeNumber1 = data.employeeNumber;
        console.log(name1, age1, employeeNumber1);
    
        var name2 = data['name'];
        var age2 = data['age'];
        var employeeNumber2 = data['employeeNumber'];
        console.log(name2, age2, employeeNumber2);
    </script>
    </body>
    </html>
    
    动态设置自定义属性

    动态设置自定义属性获取语法:

    Element.dataset.属性名 = '属性值' 或 Element.dataset['属性名'] = '属性值'
    

    示例:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
    </head>
    <body>
    <div id="person">车间员工</div>
    <button id="change">切换员工</button>
    <script>
        var element = document.querySelector("#person");
        element.dataset.name = 'Tom';
        element.dataset.age = '30';
        element.dataset.employeeNumber = '002';
    
        var data1 = document.querySelector("#person").dataset;
        var name1 = data1.name;
        var age1 = data1.age;
        var employeeNumber1 = data1.employeeNumber;
        console.log(name1, age1, employeeNumber1);
        
        document.querySelector("#change").onclick = function()
        {
            element.dataset['name'] = 'Jack';
            element.dataset['age'] = '28';
            element.dataset['employeeNumber'] = '003';
    
            var data2 = document.querySelector("#person").dataset;
            var name2 = data2.name;
            var age2 = data2.age;
            var employeeNumber2 = data2.employeeNumber;
            console.log(name2, age2, employeeNumber2);
        }
    </script>
    </body>
    </html>
    

    相关文章

      网友评论

        本文标题:HTML5 - 自定义属性

        本文链接:https://www.haomeiwen.com/subject/ggjiuqtx.html