【问题标题】:How to store object in a cookie so I can use it for further sessions?如何将对象存储在 cookie 中以便我可以将其用于进一步的会话?
【发布时间】:2022-01-25 03:22:25
【问题描述】:

嗨,

我有这样的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 中的值看起来像这样:[object CSS properties]。这是为什么?如何正确存储值?

谢谢。

【问题讨论】:

    标签: javascript object cookies


    【解决方案1】:

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

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

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

    并检索

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

    【讨论】:

      【解决方案2】:

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

      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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-06
        • 1970-01-01
        • 1970-01-01
        • 2016-03-24
        • 2016-12-16
        • 1970-01-01
        • 2011-03-01
        • 1970-01-01
        相关资源
        最近更新 更多