如何将对象存储在cookie中,以便我可以使用它进行进一步的会话



嗨,

我有这样的html:

<div id="inputarea" style="color:black;font-size:15px;">

我想把风格数据存储到cookie中,所以我这样做了:

setCookie('savedstyle',inputarea.style);

因此,在我的下一个会话中,inputarea应该从cookie中加载数据,并将其设置为inputarea的样式,如下所示:

if(getCookie('savedstyle')) {
inputarea.style = getCookie('savedstyle');
}

什么也没发生,因为存储在cookie中的值看起来像这样:[对象CSS属性]。为什么?如何正确存储价值?

谢谢。

JS中的.style只存储CSS属性的setter。它对阅读信息没有用处。

如果您只想存储内联样式,请使用:

setCookie('savedstyle', inputarea.getAttribute('style'))

并检索

inputarea.setAttribute('style', getCookie('savedstyle'))

试试这些。这些是我在项目需要时使用的一些样板函数。

readCookie = (cname) =>
{
let name = cname + '=';
let decodedCookie = decodeURIComponent(window.document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) 
{
let c = ca[i];
while (c.charAt(0) == ' ') 
{
c = c.substring(1);
}
if (c.indexOf(name) == 0)
{
return c.substring(name.length, c.length);
}
}
return '';
}
createCookie=(cname, cvalue)=>
{
let d = new Date();
d.setTime(d.getTime() + (10*24*60*60*1000));
let expires = 'expires='+ d.toUTCString();
window.document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
}
deleteCookie = (name) =>
{
if(readCookie(name)) 
{
window.document.cookie = name + '=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT';
}
}

readCookie函数通过名称读取cookie。createCookie您给它一个名称和值,deleteCookie会按名称删除cookie。非常不言自明:D。

相关内容

最新更新