浏览器本地缓存localStorage

本文介绍了一种使用JavaScript操作Web浏览器本地存储的方法,包括保存、读取及清除localStorage数据。此外,还提供了一个实用示例,展示如何将文本区域的内容缓存到浏览器中,并在下次访问时恢复这些内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值