简体   繁体   English

使用 JavaScript 在 localStorage 中存储多个 ID

[英]Storing multiple ID's in localStorage using JavaScript

I am wanting to add a favorites function for my website.我想为我的网站添加收藏夹功能。 The technologies I am using are html, css, javascript and json.我使用的技术是 html、css、javascript 和 json。 I am loading the json file thru ajax.我正在通过 ajax 加载 json 文件。 A user is able to search for a device and add that device to their favourites and that is done via sessionStorage and localStorage, but my problem is when a user clicks on a new phone to add to their favorite, it overrides it.用户能够搜索设备并将该设备添加到他们的收藏夹,这是通过 sessionStorage 和 localStorage 完成的,但我的问题是当用户单击新手机以添加到他们的收藏夹时,它会覆盖它。 Do I have to put like an IF statement which will say if there is an id there still add this one.我是否必须像一个 IF 语句那样说如果有一个 id 仍然添加这个。 I am confused on how to do this...我对如何做到这一点感到困惑......

Code Samples....代码示例....

$(document).on('click', '.productfavourite', function(event) { 

  // whichever HTML element has been clicked,
  // grab the id of that and set it as product fave
  productFave = event.target.id;

  localStorage.setItem('productFave', productFave);
  console.log(productFave);
  window.location="favourites.html";
});

I would suggest you save the selected items in an object or array before you write it in to the localStorage.我建议您在将所选项目写入 localStorage 之前将其保存在对象或数组中。 After that you convert the object or array to a json string.之后,您将对象或数组转换为 json 字符串。

var selected = [];
$(document).on('click', '.productfavourite', function(event) {
    selected.push(event.target.id);
    console.log(selected);
});

this returns an array that your can convert to json.这将返回一个您可以转换为 json 的数组。 Hope this helps.希望这可以帮助。

So what you need is to keep a collection (list or dictionary) containing the favorites.所以你需要的是保留一个包含收藏夹的集合(列表或字典)。 I'll give you some examples, then you can figure out the rest.我给你举几个例子,然后你就可以弄清楚剩下的。

You get the current productFav in your localStorage as follows:您可以按如下方式在 localStorage 中获取当前productFav

var fav = localStorage.getItem("productFav") || [];

Now you don't want to store one value in localStorage, you want your whole list there.现在您不想在 localStorage 中存储一个值,而是希望将整个列表存储在那里。 So you add the new favorites to the list and serialize the result as a json string因此,您将新的收藏夹添加到列表中并将结果序列化为 json 字符串

fav.push(newItem);

localstorage.setitem("productfav", JSON.stringify(fav));

I assumed fav is a list.我认为fav是一个列表。 It's best to use a dictionary if you want to avoid adding duplicated entries如果您想避免添加重复条目,最好使用字典

You can also try:你也可以试试:

if(Storage !== "undefined") {
   localStorage.setItem("productFave", localStorage.getItem("productFave")+ ", newItemValue3");
}

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

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