1.API
setItem (key, value) —— 保存数据,以键值对的方式储存信息。
getItem (key) —— 获取数据,将键值传入,即可获取到对应的value值。
removeItem (key) —— 删除单个数据,根据键值移除对应的信息。
clear () —— 删除所有的数据
key (index) —— 获取某个索引的key
2、localStorage
localStorage的生命周期是永久性的。假若使用localStorage存储数据,即使关闭浏览器,也不会让数据消失,除非主动的去删除数据,localStorage有length属性,可以查看其有多少条记录的数据。
使用方法如下:
var storage = null;
if(window.localStorage){ //判断浏览器是否支持localStorage
storage = window.localStorage;
storage.setItem("name", "Rick"); //调用setItem方法,存储数据
alert(storage.getItem("name")); //调用getItem方法,弹框显示 name 为 Rick
storage.removeItem("name"); //调用removeItem方法,移除数据
alert(storage.getItem("name")); //调用getItem方法,弹框显示 name 为 null
}
3、sessionStorage
sessionStorage 的生命周期是在浏览器关闭前。也就是说,在整个浏览器未关闭前,其数据一直都是存在的。sessionStorage也有length属性,其基本的判断和使用方法和localStorage的使用是一致的。
需要注意的有以下几点:
<1> 页面刷新不会消除数据
<2>只有在当前页面打开的链接,才可以访sessionStorage的数据
<3>使用window.open打开页面和改变localtion.href方式都可以获取到sessionStorage内部的数据