document.cookie
传统方式我们以document. cookie来进行存储的,但是由于其存储大小只有4k左右,并且解析也相当的复杂,
window.localStorage和window.sessionStorage
- 容量较大:localStorage约20M,sessionStorage约5M
- localStorage永久生效,除非手动删除;存储在硬盘上;可以多窗口共享,但是不能跨浏览器;
- sessionStorage的生命周期为关闭浏览器窗口;相当于存储在当前页面的内内存中;只能在当前页面共享;
- 只能存储字符串,可以将对象JSON.stringify() 编码后存储
- SetItem(key,value):存储数据,以键值对的方式
- getItem(key):通过指定的键获取对应的值内容
- removeItem(key):删除指定的key及对应的值内容
- clear():清空所有存储内容
<script>
var userData=document.getElementById("userName");
//存储数据
document.getElementById("setData").onclick=function(){
window.localStorage.setItem("userName",userData.value);
}
//获取数据
document.getElementById("getData").onclick=function(){
var value=window.localStorage.getItem("userName");
alert(value);
}
//删除数据
document.getElementById("removeData").onclick=function(){
window.localStorage.removeItem("userName");
}
</script>