HTML5 data-* 自定义属性

在jQuery的attr与prop提 到过在IE9之前版本中如果使用property不当会造成内存泄露问题,而且关于Attribute和Property的区别也让人十分头痛,在 HTML5中添加了data-*的方式来自定义属性,所谓data-*实际上上就是data-前缀加上自定义的属性名,使用这样的结构可以进行数据存放。 使用data-*可以解决自定义属性混乱无管理的现状。

说明:下面代码中紫色的文字是声明data-*的两种方式。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>javascript</title>
 6     <style type="text/css">
 7         [data-birth-date]{
 8             background-color: #0f0;
 9             width:100px;
10             margin:20px;
11         }
12     </style>
13 </head>
14 <body>
15 <div id="test" data-age="25">
16     click here
17 </div>
18 </body>
19 </html>
20 <script type="text/javascript">
21     var test = document.getElementById("test");
22     test.dataset.my = "meng";
23     test.dataset.birthDate = "19910512"
24     test.onclick = function () {
25         alert(this.dataset.my + ' ' + this.dataset.age+' '+this.dataset.birthDate);
26     }
27 </script>

 比较不好的消息就是data-*的浏览器兼容性情况十分不乐观

  • Internet Explorer 10以下不支持。
原文地址:https://www.cnblogs.com/liubeimeng/p/5626885.html