sessionStorage 和localStorage

  1. 特点:
    a) 设置、读取方便
    b) 容量较大,sessionStorage约5M、localStorage约20M
    c) 只能存储字符串,可以将对象JSON.stringify() 编码后存储
  2. Window.sessionStorage的使用
    a) 特点:
    i. 生命周期为关闭浏览器窗口:相当于存储在当前页面的内内存中
    ii. 在同一个窗口下数据可以共享(在当前页面下可以获取到,换另外一个页面下不能获取到)
    b) 方法介绍:(两种存储方式的方法一致)
    i. SetItem(key,value):设置数据,以键值对的方式
    ii. getItem(key):通过指定的键获取对应的值内容
    iii. removeItem(key):删除指定的key及对应的值内容
    iv. clear():清空所有存储内容
    c) 使用说明:
<script>
    var userData=document.getElementById("userName");
    //存储数据
    document.getElementById("setData").function(){
        window.sessionStorage.setItem("userName",userData.value);
    }
    //获取数据
    document.getElementById("getData").function(){
        var value=window.sessionStorage.getItem("userName");
        alert(value);
    }
</script>

  1. Window.localStorage的使用
    a) 特点:
    i. 永久生效,除非手动删除:存储在硬盘上
    ii. 可以多窗口共享。但是不能跨浏览器
    b) 使用说明:
    和sessionStorage用法相同。
<script>
    var userData=document.getElementById("userName");
    //存储数据
    document.getElementById("setData").function(){
        window.localStorage.setItem("userName",userData.value);
    }
    //获取数据
    document.getElementById("getData").function(){
        var value=window.localStorage.getItem("userName");
        alert(value);
    }
    //删除数据
    document.getElementById("removeData").function(){
        window.localStorage.removeItem("userName");
    }
</script>

本文属个人学习整理记载

猜你喜欢

转载自blog.csdn.net/qq_43537987/article/details/89386343