本文摘自PHP中文网,作者php中世界最好的语言,侵删。
这次给大家带来H5的web本地存储如何使用,怎么使用H5的web本地存储?H5的web本地存储使用的注意事项有哪些,下面就是实战案例,一起来看一下。Web Storage是HTML5引入的一个非常重要的功能,可以在客户端本地存储数据,类似HTML4的cookie,但可实现功能要比cookie强大的多,cookie大小被限制在4KB,Web Storage官方建议为每个网站5MB。
Web Storage又分为两种:
sessionStorage
localStorage
从字面意思就可以很清楚的看出来,sessionStorage将数据保存在session中,浏览器关闭也就没了;而localStorage则一直将数据保存在客户端本地;
不管是sessionStorage,还是localStorage,可使用的API都相同,常用的有如下几个(以localStorage为例):
保存数据:localStorage.setItem(key,value);读取数据:localStorage.getItem(key);删除单个数据:localStorage.removeItem(key);删除所有数据:localStorage.clear();得到某个索引的key:localStorage.key(index);
如上,key和value都必须为字符串,换言之,web Storage的API只能操作字符串。
接下来,我们通过Web Storage开发一个简单的通讯录小程序,以演示相关API的使用方法;我们要实现如下功能:
录入联系人,联系人有姓名、手机号码2个字段,以手机号作为key存入localStorage;根据手机号码,查找机主;列出当前已保存的所有联系人信息;
首先先写一个简单的html代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!DOCTYPEHTML>
< html >
< head >
< metacharsetmetacharset = "utf-8" />
< title >H5本地存储之WebStorage篇</ title >
</ head >
< body >
< divstyledivstyle = "border:2pxdashed#ccc;width:320px;text-align:center;" >
< labelforlabelfor = "user_name" >姓名:</ label >
< inputtypeinputtype = "text" id = "user_name" name = "user_name" class = "text" />
< br />
< labelforlabelfor = "mobilephone" >手机:</ label >
< inputtypeinputtype = "text" id = "mobilephone" name = "mobilephone" />
< br />
< inputtypeinputtype = "button" onclick = "save()" value = "新增记录" />
< hr />
< labelforlabelfor = "search_phone" >输入手机号:</ label >
< inputtypeinputtype = "text" id = "search_phone" name = "search_phone" />
< inputtypeinputtype = "button" onclick = "find()" value = "查找机主" />
< pidpid = "find_result" >< br /></ p >
</ div >
< br />
< dividdivid = "list" >
</ div >
</ body >
</ html >
|
要实现联系人的保存,只需要简单实现如下JS方法即可:
1 2 3 4 5 | functionsave(){
varmobilephone=document.getElementById( "mobilephone" ).value;
varuser_name=document.getElementById( "user_name" ).value;
localStorage.setItem(mobilephone,user_name);
}
|
要实现查找机主,则实现如下JS方法:
1 2 3 4 5 6 7 | //查找数据
functionfind(){
varsearch_phone=document.getElementById("search_phone").value;
varname=localStorage.getItem(search_phone);
varfind_result=document.getElementById("find_result");
find_result.innerHTML=search_phone+"的机主是:"+name;
}
|
相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
12个冷门的H5设计小技巧
H5中怎样使用postMessage实现两个网页间传递数据
H5怎样用绘制五角星
以上就是H5的web本地存储如何使用的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
分享几款炫酷的HTML5实现的图片特效
HTML5 简介
h5手机端页面缩放
HTML5中怎么做五角星
HTML5拖放关于api实现拖放排序的实例代码
HTML5超链接字体如何改颜色
HTML5前景怎么样
HTML5中常用交互元素实现的代码实例
HTML5的本地存储indexeddb
css3如何实现元素环绕中心点布局(代码示例)
更多相关阅读请进入《HTML5》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » H5的web本地存储如何使用