美文网首页
保存localStorage

保存localStorage

作者: 羊绘霖 | 来源:发表于2017-11-01 15:25 被阅读0次

var storage =window.localStorage

//设置localStorage  name:名字value:值time:有效时间

function setStorage(name,value,time) {

var strsec =getsec(time ===undefined?'h8': time)

var exp =newDate()

var jsonObj = {'deadline': exp.setTime(exp.getTime() + strsec *1),'data': value }

var jsonStr = JSON.stringify(jsonObj)

storage.setItem(name,jsonStr)

}

//获取localStorage如果不存在返回null

function getStorage(name) {

var json = storage.getItem(name)

var jsonObj = JSON.parse(json)

var time =newDate().getTime()

if(jsonObj !==null) {

if(jsonObj['deadline'] <= time) {

removeStorage(name)

return null

}

else{

return jsonObj['data']

}

}

else{

return null

}

}

//将localStorage中的某个键值对删除

function removeStorage(name) {

storage.removeItem(name);

}

//将localStorage的所有内容清除

function clearStorage() {

storage.clear()

}

// 拓展

//获取用户Id

function getUserId(name) {

var userInfo =getStorage(name)

var userId = (userInfo ===null?'': userInfo.UserId)

return userId

}

//获取用户信息

function getUserInfo(name) {

var userInfo =getStorage(name)

if(userInfo !==null) {

setStorage(name,userInfo,'h8')

userInfo =getStorage(name)

}

// var userId = (userInfo === null ? '' : userInfo.UserId)

return userInfo

}

//这是有设定过期时间的使用示例:

// s20是代表20秒

// h是指小时,如12小时则是:h12

// d是天数,30天则:d30

function getsec(str) {

varstr1 = str.substring(1,str.length) *1

varstr2 = str.substring(0,1)

if(str2 =="s") {

return str1 *1000

}

else if(str2 =="h") {

return str1 *60*60*1000

}

else if(str2 =="d") {

return str1 *24*60*60*1000

}

}

相关文章

网友评论

      本文标题:保存localStorage

      本文链接:https://www.haomeiwen.com/subject/ljkgpxtx.html