js获取自定义data属性

时间:2023-12-09 17:00:19
<!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>