瀏覽器本地緩存localStorage

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();
        }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章