欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

浏览器本地缓存localStorage

程序员文章站 2022-07-13 11:01:36
...

web 本地存储

var storage={
    save2Local:function (key,val) {
        localStorage.setItem(key,val);
    },
    restore4Local:function(key) {
    if (window.localStorage) {
        return localStorage.getItem(key);
    }
},
/***
 * 清除localStorage
 */
removeLocalStorage:function (key) {
    if(key){
        localStorage.removeItem(key);
    }
}

};

 

应用:

 var currentDateTime=new Date();
        var date_format='%Y%m%d';
        var currentDate=currentDateTime.format2(date_format);//20170316
        console.log('currentDate:'+currentDate);
        //缓存到浏览器
        var browserCache=function (prefix) {
            var answer=$('textarea[name=content]').val();
            if(answer){//每次currentDate 都需要重新生成
                currentDate=new Date().format2(date_format);//20170316
                storage.save2Local(prefix+currentDate,answer);
            }
        };
        //从浏览器中获取缓存
        var getbrowserCache=function (prefix) {
            var answer=storage.restore4Local(prefix+currentDate);
            if(!answer){
                currentDateTime.setDate(currentDateTime.getDate() - 1);
                currentDate=currentDateTime.format2(date_format);//20170316
                answer=storage.restore4Local(prefix+currentDate);
            }
            answer&&$('textarea[name=content]').val(answer).focus();
        }

 

 

相关标签: localStorage