我是靠谱客的博主 纯情豌豆,这篇文章主要介绍H5的web本地存储如何使用,现在分享给大家,希望可以做个参考。

这次给大家带来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; }
登录后复制

相信看了这些案例你已经掌握了方法,更多精彩请关注靠谱客其它相关文章!

相关阅读:

12个冷门的H5设计小技巧

H5中怎样使用postMessage实现两个网页间传递数据

H5怎样用绘制五角星

以上就是H5的web本地存储如何使用的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是纯情豌豆最近收集整理的关于H5的web本地存储如何使用的全部内容,更多相关H5内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(104)

评论列表共有 0 条评论

立即
投稿
返回
顶部