Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

HTML系列之data-属性 #3

Open
yuanyuanbyte opened this issue Nov 12, 2021 · 0 comments
Open

HTML系列之data-属性 #3

yuanyuanbyte opened this issue Nov 12, 2021 · 0 comments

Comments

@yuanyuanbyte
Copy link
Owner

在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-*属性被使用的目的,这个方法也用到我们以前使用自定义属性。

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant