我的家園

          我的家園

          簡單的HTML5 Web Storage留言冊

          Posted on 2012-04-15 16:37 zljpp 閱讀(152) 評論(0)  編輯  收藏

          在這用一個簡單的示例在講解一下如何利用Web Storage來保存和讀取數(shù)據(jù)。

          示例HTML代碼如下:

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
          <html xmlns="http://www.w3.org/1999/xhtml">
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
          <title>HTML5 WebStorage 留言本</title>
          <script type="text/javascript" src="JS/liuyanben.js"></script>
          </head>
          <body>
          <h3>HTML5 WebStorage 留言本</h3>
          <textarea id="demo" cols="60" rows="10"></textarea><br />
          <input type="button" value="留言" onclick="savelocalStorage('demo');" />
          <input type="button" value="清除留言" onclick="clearlocalStorage('msg');" />
          <hr />
          <p id="msg"></p>
          </body>
          </html>

          示例所用到的liuyanben.js 代碼如下:

          // JavaScript Document
          function savelocalStorage(id){
          var data=document.getElementById(id).value;
          var time=new Date().getTime();
          localStorage.setItem(time,data);
          loadlocalStorage('msg');
          }

          function loadlocalStorage(id){
          var result='<table border="1">';
          for(var i=0;i<localStorage.length;i++){
          var key=localStorage.key(i);
          var value=localStorage.getItem(key);
          var date=new Date();
          date.setTime(key);
          var datestr=date.toGMTString();
          result +='<tr><td>'+value+'</td><td>'+datestr+'</td></tr>';
          }
          result +='</table>';
          var target = document.getElementById(id);
          target.innerHTML=result;
          }

          function clearlocalStorage(){
          localStorage.clear();
          loadlocalStorage('msg');
          alert("localStorage留言已被清除!");
          }

          通過我們發(fā)現(xiàn)這個JS代碼中有三個調用的函數(shù),savalocalStorage、loadlocalStorage和clearlocalStorage。

          1.savalocalStorage:使用new Date().getTime()得到當前時間,調用loadlocalStorage,將時間保存為鍵名,將文本框中的保存為鍵值,再調用localStorage函數(shù)在頁面上顯示保存的數(shù)據(jù)。


          2.loadlocalStorage:取得數(shù)據(jù)用到了localStorage.length和localStorage.key兩個重要的localStorage函數(shù)。localStorage.length是所有保存在localStorage中的數(shù)據(jù)條數(shù),localStorage.key是將數(shù)據(jù)的索引號做為index傳入,可以得到索引號對應的數(shù)據(jù)。索引從0開始,如第2條數(shù)據(jù)的所以號是1。


          3.clearlocalStorage:利用localStorage中的clear方法,清除保存在localStorage中的全部數(shù)據(jù)。

          注:為什么以日期和時間來做為鍵名?因為日期和時間的值是以時間戳的形式進行管理,所以不可能存在重復的鍵名。


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 阳谷县| 娱乐| 肃北| 永胜县| 清徐县| 雅安市| 淮南市| 翼城县| 兰考县| 姚安县| 清苑县| 安国市| 绥中县| 双鸭山市| 噶尔县| 赤峰市| 太仆寺旗| 绵竹市| 边坝县| 武宣县| 屏南县| 克什克腾旗| 临安市| 视频| 灵台县| 梓潼县| 南平市| 同仁县| 枣庄市| 门头沟区| 乐山市| 山阴县| 洛川县| 崇仁县| 大渡口区| 民和| 依安县| 万州区| 新龙县| 陕西省| 堆龙德庆县|