让前端飞Web前端之路

Web Storage

2019-08-03  本文已影响7人  意蜀

关于Web Storage的那些事

if(typeof(Storage)=='undefined'){
      alert('您的浏览器不支持Web Storage');
    }
else{
    //localSorage和sessionStorage...
}

localStoragesessionStorage

初探localStorage

1.访问localStorage

window.localStorage.setItem(key,value);
window.localStorage.setItem('userdata','hello world');//存储
window.localStorage.getItem(key);
window.localStorage.getItem('userdata');//读取'hello world'
window.localStorage['userdata']='hello world';//存储
var value=window.localStorage['userdata'];//读取'hello world'
window.localStorage.userdata='hello world';//存储
var value=window.localStorage.userdata;//读取'hello world'

2.删除localStorage

localSorage.clear();
window.localStorage.remove('userdata');//remove()方法删除
delete window.localStorage.userdata;//属性删除
delete window.localStorage['userdata'];//数组索引删除


初探sessionStorage

1.存储(类似locaStorage)

window.sessionStorage.setItem(key,value);
window.sessionStorage.setItem('userdata','hello world');//存储
window.sessionStorage['userdata']='hello world';//存储
window.sessionStorage.userdata='hello world';//存储

2.读取

window.sessionStorage.getItem('userdata');//读取'hello world'
var value=window.sessionStorage.userdata;//读取'hello world'
var value=window.sessionStorage['userdata'];//读取'hello world'

3.删除

sessionSorage.clear();
window.sessionStorage.remove('userdata');//remove()方法删除
delete window.sessionStorage.userdata;//属性删除
delete window.sessionStorage['userdata'];//数组索引删除

例子

题目
新建 HTML 页面,实现如下功能,并截图上传(文档页面图+Console面板下的Application面板图):
页面中显示一个数字,初始为0。(数据要从Localstorage中读取)
页面中有一个 加号按钮,每点击一次,上方数字就加一。(数据要存储在Localstorage中)
刷新页面,顶部数字不归零。
代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    #show{
        background-color: orange;
        height: 30px;
        width: 30px;
        text-align: center;
    }
    #add{
        background-color: orchid;
        height: 30px;
        width: 30px;
        text-align: center;
    }
    </style>
    <script>
     function onLoad(){
          if(typeof(Storage)=='undefined'){
              alert('您的浏览器不支持');
          }else{
                show.addEventListener('click',readFromLocalStorage);
              add.addEventListener('click',addFromLocalStorage);
          }
        }
        function readFromLocalStorage(){
            window.localStorage.num=0;
            show.innerHTML=localStorage.num;
        }
        function addFromLocalStorage(){
            show.innerHTML=++localStorage.num;
        }
    </script>
</head>
<body onload="onLoad()">
    <div id="show">0</div>
    <div id="add">+</div>
</body>
</html>

结果

运行前
运行中
刷新页面后
上一篇下一篇

猜你喜欢

热点阅读