html —— data-*自定义属性

一、基本说明

文档说明:

The data-* global attributes form a class of attributes, called custom data attributes, allows proprietary information to be exchanged between the HTML and its DOM representation that may be used by scripts. All such custom data are available via the HTMLElement interface of the element the attribute is set on. The HTMLElement.dataset property gives access to them.

data-*全局属性形成一个属性类,称作自定义数据属性,允许专有的(proprietary adj,专有的,专利的,所有(人)的;n,所有权)信息被改变,在HTML 与对应的可能被用于script 的DOM 对象之间。所有这些自定义数据都是可通过(via prep,通过,经过)设置了这个属性的元素的HTMLElement 接口获取的,然后可通过HTMLElement.dataset属性访问到该属性值。*可被任意合法的命名代替,所谓合法,是指遵循下面的规则:

只可包含字母、数字和以下字符:dash(-)、dot(.)、colon(:)、underscore(_)。此外不能包含大写的ASCII码字母(务必记住!)。

Note that the HTMLElement.dataset property is a StringMap and the name of the custom data attribute data-test-value will be accessible via HTMLElement.dataset.testValue as any dash (U+002D) is replaced by the capitalization of the next letter (camelcase).

记住HTMLElement.dataset 属性是一个StringMap映射表,且这个自定义属性的名字(例data-test-value)将通过HTMLElement.dataset.testValue 被访问因为所有的dash(破折号)将被下一个字母的大写形式代替。(即访问自定义的data-test-value属性时,使用的是对应的testValue,见例子)

原网页:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Global_attributes/data-*


二、简单使用

data-*自定义元素的命名可有多个破折号,访问时规则一致:

<!DOCTYPE html>
<html>
<head>
	<title>测试data-*自定义属性</title>
	<meta charset="utf-8">
</head>
<body>
	<div id="test" data-test-custom-attr="20"></div>
	<script type="text/javascript">
		var firstTimeValue=document.getElementById("test").dataset.testCustomAttr;
		document.getElementById("test").dataset.testCustomAttr=50;
		var SecondTimeValue=document.getElementById("test").dataset.testCustomAttr;
		alert(firstTimeValue+" "+SecondTimeValue);
	</script>
</body>
</html>
提示结果为:20  50


HTMLElement.dataset方法基础支持:Chrome 8、Firefox 6.0、IE 11、Opera 11.1、Safari 6。

见:https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement/dataset

可用一般方法替代:

HTMLElement.setAttribute(‘attriName’,‘value’);

HTMLElement.getAttribute("attriName");


个人感悟:当需要的自定义属性不多,且易于管理时,可用在script中声明的变量代替这些属性值的作用。






  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值