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

有这么一段描述:

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.

接下来我们就可以实现这样一个简单例子:

<!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>

上面的li标签中嵌入一些data-*特性,当你点击那个span,读取了每个data-*的value, 最后实现一个切换文字效果。你有注意到上面js中有用到一个dataset属性。W3C官方也是有关于dataset的介绍。上面的代码测试通过在 Firefox 11.0, Chrome 18.0.1025.151
注意这个在IE9是不支持的。 IE9 需要改写为getAttribute

<!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>


上面的代码在IE 9.0.8112测试通过。您也可以在IE, FF中单步调试js看其中结果

希望对您Web开发有帮助。

您可能感兴趣的文章:

HTML5的智能提示在VisualStudio2010

 


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on 2012-04-09 11:26  PetterLiu  阅读(22433)  评论(1编辑  收藏  举报