data 自定义属性
- 在标签中定义data自定义属性:data-key=“value”;
- 在js操作该元素的 data 自定义属性:el.dataset
- 获取:el.dataset.key
- 设置: el.dataset.key = “value”
注意自定义属性:“data-”开头,但溜_x_i_a_o_迪童鞋自行想象自定义属性,尝试失败了!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box" data-definition="Custom"></div>
<script>
{
let box = document.querySelector("#box");
console.log(box.definition);
}
</script>
</body>
</html>
正确方式:通过dataset属性获取
let box = document.querySelector("#box");
//console.log(box.data-definition);
console.log(box.dataset.definition);
也可直接进行修改
let box = document.querySelector("#box");
//console.log(box.data-definition);
console.log(box.dataset.definition);
box.dataset.definition = "自定义属性";
console.log(box.dataset.definition);
自定义属性和Attributes(上一节有说明:DOM属性操作及ECMA、DOM 的属性操作的区别)一样存在文档中,只能是字符串,可通过JS操作html中的自定义属性,最终会呈现在html文档中。
let box = document.querySelector("#box");
box.dataset.definition = "自定义属性";
box.dataset.xiaodi = '6666';
(后续待补充)