js获取自定义data属性
<!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>
相关文章
发表评论
评论列表
- 这篇文章还没有收到评论,赶紧来抢沙发吧~