码迷,mamicode.com
首页 > Web开发 > 详细

js获取自定义data属性

时间:2020-02-27 19:06:11      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:bsp   span   ase   方便   charset   自定义   div   leaves   style   

<!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属性

标签:bsp   span   ase   方便   charset   自定义   div   leaves   style   

原文地址:https://www.cnblogs.com/QW-lzm/p/12373523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!