美文网首页
JS获取自定义属性data值

JS获取自定义属性data值

作者: beijing_beijing | 来源:发表于2017-06-02 16:02 被阅读0次
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    <div id="tree" data-leaves="47" data-plant-height="2.4m"></div>
    <script>
        var tree = document.getElementById("tree");
        //getAttribute()取值属性
        console.log(tree.getAttribute("data-leaves"));
        console.log(tree.getAttribute("data-plant-height"));
        //setAttribute()赋值属性
        tree.setAttribute("data-leaves","48");
    
        //data-前缀属性可以在JS中通过dataset取值,更加方便
        console.log(tree.dataset.leaves);
        console.log(tree.dataset.plantHeight);
        //赋值
        tree.dataset.plantHeight = "3m";
        tree.dataset.leaves--;
        //新增data属性
        tree.dataset.age = "100";
        //删除,设置成null,或者delete
        tree.dataset.leaves = null;
        delete tree.dataset.age;
    
        //jQuery的data方法
        var $tree = $('#tree');
        console.log($tree.data("plant-height"));
    </script>
    
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:JS获取自定义属性data值

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