例如:
代码如下:
使用attribute方法存取 data-* 自定义属性的值
使用attributes方法存取 data-* 自定义属性的值非常方便:
代码如下:
// 使用getAttribute获取 data- 属性
var user = document . getElementById ( 'user' ) ;
var userName = plant . getAttribute ( 'data-uname' ) ; // userName = '脚本之家'
var userId = plant . getAttribute ( 'data-uid' ) ; // userId = '12345'
// 使用setAttribute设置 data- 属性
user . setAttribute ( 'data-site' , 'http://www.gxlcms.com' ) ;
此方法能在所有的现代浏览器中正常工作,但它不是HTML 5 的自定义 data-*属性被使用目的,不然和我们以前使用的自定义属性就没有什么区别了,例如:
代码如下: