1. 程式人生 > >localStorage和sessionStorage使用

localStorage和sessionStorage使用

默認 是否 color new undefined span gettime data clas

localStorage.setItem("key","value");//存數據
localStorage.getItem("key");//取數據
localStorage.removeItem("key");//刪除數據
localStorage.clear();?//清空數據

sessionStorage用法和localStorage一樣

這裏簡單封裝了一個,默認緩存7天,獲取數據時判斷數據是否過期

function localStorage_set(key, value , exp) {
    if (typeof exp == "undefined") {
        //默認緩存7天時間
exp = 1000 * 60 * 60 * 24 * 7; } var curTime = new Date().getTime(); localStorage.setItem(key, JSON.stringify({data: value, time: curTime, exp: exp})); } function localStorage_get(key) { var data = localStorage.getItem(key); if(data == null){ return null; } var
dataObj = JSON.parse(data); if (new Date().getTime() - dataObj.time > dataObj.exp) { localStorage.removeItem(key); return null; } else { var dataObjDatatoJson = JSON.parse(dataObj.data) return dataObjDatatoJson; } }

localStorage和sessionStorage使用