yuanyuanbyte / Blog

圆圆的博客,预计写七个系列:JavaScript深入系列、JavaScript专题系列、网络系列、Webpack系列、Vue系列、JavaScript基础系列、HTML&CSS应知应会系列。

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

HTML系列之data-属性

yuanyuanbyte opened this issue · comments

在HTML5中我们可以使用data-*(自定义数据属性)为前缀来设置我们需要的自定义属性,来进行一些数据的存取。

如何使用?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="div1" class="div1" data-id="myId" data-id-and-class="Hello">test2</div>
    <div id="div2" myName="Hello">test</div>
    <script>
        var div1 = document.getElementById("div1");
        //获取自定义的值
        var myId = div1.getAttribute("data-id");
        var my = div1.getAttribute("data-id-and-class");
        console.log(myId); // myId
        console.log(my); // Hello
        
        //设置自定义的值
        div1.setAttribute("data-name", "nicai")

        var div = document.getElementById("div2");
        var myName = div.getAttribute("myName");
        console.log(myName); //Hello
        </script>
</body>
</html>

getAttribute方法能在所有现代浏览器中正常工作,但它不是HTML5的自定义data-*属性被使用的目的,这个方法也用到我们以前使用自定义属性。