简体   繁体   English

如何创建一个在页面上存储多个值的cookie按钮

[英]How to create a one cookie button that stores multiple values across pages

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): 每次单击同一按钮时,我都使用以下代码来设置Cookie,每次单击该cookie时数字值都会增加,并将产品标题保存为该值(例如,名称:1,值: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: 它在我的页面上很好地工作,每次单击时都设置一个新的cookie名称,依次为“ 1”,“ 2”,“ 3”,依此类推,但显然,这让我有了:

  • Name: 1 Value: Car 名称:1值:汽车
  • Name: 2 Value: Car 名称:2价值:汽车
  • Name: 3 Value: Car 名称:3价值:车

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. 但是,当我转到另一个页面并再次单击该按钮时,它将覆盖名称为1的cookie并再次启动该过程。

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 名称:1值:汽车
  • Name: 2 Value: Bike 名称:2值:自行车
  • Name: 3 Value: Train 名称:3价值:火车

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. 我知道为每个页面创建新按钮会更容易,但是我在Wesbite上使用了模板系统,并且我们有成千上万的产品页面,所以这对我来说不是一个可行的选择。

Is pretty easy storing an array of objects, is better in my opinion using localStorage instead of cookie. 我很容易存储对象数组,在我看来,最好使用localStorage而不是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/ 这里的例子https://jsfiddle.net/0kp9s2bv/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM