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 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题