dongshuzui0335 2018-08-21 14:19
浏览 663

如何创建一个cookie按钮,跨页面存储多个值

I am using the following code to set a cookie each time the same button is clicked, which has an increased numberical value each time it is clicked and saves the title of the product as the value (for example Name: 1, Value: Car):

var num=1;
  function addCookie() {

        var expString = "; expires=" + date.toGMTString();
        var cookievalue=escape(document.querySelector("[name=addpart]").value) + ";";
        document.cookie=num + "=" + cookievalue + expString + "; path=/"; 
        num++;
    }

It works nicely on my page, setting a new cookie name each time it is clicked as '1', then '2', then '3' and so on, but obviously that just leaves me with:

  • Name: 1 Value: Car
  • Name: 2 Value: Car
  • Name: 3 Value: Car

However, when I go to another page and click the button again, it overwrites the cookie with the name 1 and starts the process again.

I would like to know how I can continue the name count for this button across pages? So that the user can browse the products and click the button which essentially produces a list that can be called later:

  • Name: 1 Value: Car
  • Name: 2 Value: Bike
  • Name: 3 Value: Train

I understand it would be easier to create new buttons for each page, but I use a template system on my wesbite and we have thousdands of product pages so that's not a viable option for me.

  • 写回答

1条回答

  • dongxuan58311366668 2018-08-21 14:39
    关注

    Is pretty easy storing an array of objects, is better in my opinion using localStorage instead of cookie.

    //example of first structure
    localStorage.setItem("visits", JSON.stringify({"1":[],"2":[],"3":[]}));
    
    //getting the item
    var visits = JSON.parse(localStorage.getItem("visits"));
    
    //different visits
    
    visits["1"].push("Car");
    visits["1"].push("Bike");
    visits["1"].push("Something");
    
    visits["2"].push("Bike");
    visits["2"].push("Bike");
    visits["2"].push("Something");
    
    visits["3"].push("Something");
    visits["3"].push("Something");
    visits["3"].push("Something");
    
    //setting the item
    localStorage.setItem("visits", JSON.stringify(visits));
    
    console.log(visits)
    

    Example here https://jsfiddle.net/0kp9s2bv/

    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献