localStorage.setItem("key","value");//存数据 localStorage.getItem("key");//取数据 localStorage.removeItem("key");//删除数据 localStorage.clear();//清空数据
sessionStorage使用用法和localStorage一样
sessionStorage是会话缓存
localStorage是持久缓存
这里简单封装了一个,默认缓存7天,获取数据时判断数据是否过期
/** * 设置缓存数据 * 默认缓存一个星期 * @param key * @param value * @param exp 缓存时间(d天数,h小时,m分钟,s秒【例:7d=7天,7h=7小时,7m=7分钟】) */ function lStorage_set(key,value,exp) { var timestamp = new Date().getTime(); if(typeof exp != "undefined"){ if (endWith(exp,'d')) { exp = timestamp + parseInt(exp.replace('d','')) * 1000 * 60 * 60 * 24; } else if(endWith(exp,'h')){ exp = timestamp + parseInt(exp.replace('h', '')) * 1000 * 60 * 60; } else if (endWith(exp, 'm')) { exp = timestamp + parseInt(exp.replace('m', '')) * 1000 * 60; } else if (endWith(exp, 's')) { exp = timestamp + parseInt(exp.replace('s', '')) * 1000; } else { exp = timestamp + exp; } }else{
exp = timestamp + (1000 * 60 * 60 * 24 * 7);
} localStorage.setItem(key, JSON.stringify({data: value, exp: exp})); } /** * 获取缓存数据 * @param key * @returns {null} */ function lStorage_get(key) { var data = localStorage.getItem(key); if(data == null){ return null; } var timestamp = new Date().getTime(); var dataObj = JSON.parse(data); if(timestamp < dataObj.exp){ return dataObj.data; }else{ localStorage.removeItem(key); return null; } }
/** * 判断data结尾是否是end * @param data * @param end * @returns {boolean} */ function endWith(data,end){ var d = data.length - end.length; return (d >= 0 && data.lastIndexOf(end) == d); }