Html 5中自定义data-*特性

[color=cyan][size=large]Html 5中自定义data-*特性[/size][/color]

[b]Html 5中支持用户自定义的data-*特性,它们在UI是不可见的。例如data-length,它可以附加在input的标签上。更加具体信息可参考W3C Html 5 data-说明书[/b]

[b]有这么一段描述:[/b]

[table]
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
[/table]
[b]
接下来我们就可以实现这样一个简单例子:[/b]

<!DOCTYPE html>
<html>
<head>
<title>Html5 custom data attribute Test</title>
</head>
<body >
<li class="user" data-name="Peter Liu" data-city="ShangHai"
data-lang="CSharp" data-food="apple">
<b>Peter says:</b> <span>Hello, how are you?</span>
</li>
<script type="text/javascript">
var user = document.getElementsByTagName("li")[0];
var pos = 0, span = user.getElementsByTagName("span")[0];

var phrases = [
{ name: "city", prefix: "I am from " },
{ name: "food", prefix: "I like to eat " },
{ name: "lang", prefix: "I like to program in " }
];

user.addEventListener("click", function () {
var phrase = phrases[pos++];
// Use the .dataset property
span.innerHTML = phrase.prefix + user.dataset[phrase.name];
}, false);

</script>
</body>
</html>


[color=cyan][b]
上面的li标签中嵌入一些data-*特性,当你点击那个span,读取了每个data-*的value, 最后实现一个切换文字效果。你有注意到上面js中有用到一个dataset属性。W3C官方也是有关于dataset的介绍[url]http://www.w3.org/TR/2012/WD-html5-20120329/global-attributes.html#dom-dataset[/url]。上面的代码测试通过在 Firefox 11.0, Chrome 18.0.1025.151
注意这个在IE9是不支持的。 IE9 需要改写为getAttribute [/b][/color]



<!DOCTYPE html>
<html>
<head>
<title>Html5 custom data attribute Test</title>
</head>
<body >
<li class="user" data-name="Peter Liu" data-city="ShangHai"
data-lang="CSharp" data-food="apple">
<b>Peter says:</b> <span>Hello, how are you?</span>
</li>
<script type="text/javascript">
var user = document.getElementsByTagName("li")[0];
var pos = 0, span = user.getElementsByTagName("span")[0];

var phrases = [
{ name: "city", prefix: "I am from " },
{ name: "food", prefix: "I like to eat " },
{ name: "lang", prefix: "I like to program in " }
];

user.addEventListener("click", function () {
var phrase = phrases[pos++];
// Use the .dataset property
span.innerHTML = phrase.prefix + user.getAttribute('data-'+phrase.name);
}, false);

</script>
</body>
</html>



[color=cyan][b]
上面的代码在IE 9.0.8112测试通过。您也可以在IE, FF中单步调试js看其中结果[/b][/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值