Home  >  Article  >  Web Front-end  >  简单的HTML5 Web Storage留言册

简单的HTML5 Web Storage留言册

PHP中文网
PHP中文网Original
2016-05-17 09:08:231216browse

简单的HTML5 Web Storage留言册

  在这用一个简单的示例在讲解一下如何利用Web Storage来保存和读取数据。


  示例HTML代码如下:





HTML5 WebStorage 留言本


HTML5 WebStorage 留言本




  示例所用到的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='';
for(var i=0;i';
}
result +='
'+value+''+datestr+'
'; var target = document.getElementById(id); target.innerHTML=result; } function clearlocalStorage(){ localStorage.clear(); loadlocalStorage('msg'); alert("localStorage留言已被清除!"); }


  通过我们发现这个JS代码中有三个调用的函数,savalocalStorage、loadlocalStorage和clearlocalStorage。


  1.savalocalStorage:使用new Date().getTime()得到当前时间,调用loadlocalStorage,将时间保存为键名,将文本框中的保存为键值,再调用localStorage函数在页面上显示保存的数据。


  2.loadlocalStorage:取得数据用到了localStorage.length和localStorage.key两个重要的localStorage函数。localStorage.length是所有保存在localStorage中的数据条数,localStorage.key是将数据的索引号做为index传入,可以得到索引号对应的数据。索引从0开始,如第2条数据的所以号是1。


  3.clearlocalStorage:利用localStorage中的clear方法,清除保存在localStorage中的全部数据。


  注:为什么以日期和时间来做为键名?因为日期和时间的值是以时间戳的形式进行管理,所以不可能存在重复的键名。

以上就是简单的HTML5 Web Storage留言册的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn