1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <div id = "user" uid = "12345" data-uname = "愚人码头" data-date-of-birth> </div> 9 <script> 10 // 使用getAttribute获取 data- 属性 11 var user = document . getElementById ( 'user' ) ; 12 var userName = user .dataset.uname; // userName = '愚人码头' 13 var userId = user . getAttribute ( 'uid' ) ; // userId = '12345' 14 15 // 使用setAttribute设置 data- 属性 16 user . setAttribute ( 'site' , 'http://www.css88.com' ) ; 17 console.log(1111,userName,userId,user.getAttribute('site')) 18 19 20 var dateofbirth = user.dataset.dateOfBirth = '1985-01-05'; // 设置data-date-of-birth的值. 21 console.log(dateofbirth,"dataset属性只有在Chrome 8+ Firefox(Gecko) 6.0+ Internet Explorer 11+ Opera 11.10+ Safari 6+浏览器中实现") 22 user.dataset.someDataAttr = 'mydata';//即使不存在的属性一旦挂上去之后就有了,认真脸 23 console.log('someDataAttr' in user.dataset);//true 24 25 </script> 26 </body> 27 </html>