陈斌彬的技术博客

Stay foolish,stay hungry

HTML5 中自定义 Data 特性

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的介绍

注意这个在 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>