我正试图用本地存储设置未来的到期日,但当我添加新的时
未来时间日期总是设置在当前时间。我希望在不使用cookie的情况下加载第一页后,将attr设置为div。
以下是我的功能:
if (localStorage.getItem("init") === null) {
const item = {
value: value,
expiry: new Date().getTime() + ttl,
}
localStorage.setItem(key, JSON.stringify(item))
}
}
// REMOVE KEY
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key)
// if the item doesn't exist, return null
if (!itemStr) {
return null
}
const item = JSON.parse(itemStr)
const now = new Date()
// compare the expiry time of the item with the current time
if (now.getTime() > item.expiry) {
// If the item is expired, delete the item from storage
// and return null
localStorage.removeItem(key)
return null
}
return item.value
}
setWithExpiry('init', 'true', 300);
getWithExpiry('init');
if (localStorage.getItem("init") !== null) {
// add data-cp attr to inv code
ins.setAttribute('data-cp-first', 'true');
}
我通过调整TTL解决了这个问题,我的TTL不是以毫秒为单位设置的,这就是为什么它没有将到期日期设置为未来日期。1周至毫秒=604800000毫秒
使用相同的信息:https://www.sohamkamani.com/javascript/localstorage-with-ttl-expiry/
以下是我们如何实现这一目标的概述:
Store the expected time of expiry along with the original information to be stored
When getting the item, compare the current time with the stored expiry time
If the current time is greater than to stored expiry time, return null and remove the item from storage, otherwise, return the original information.