如何创建唯一值列表并系统地将它们存储在本地存储器中

how do I create list of unique values and systematically store them in localstorage

本文关键字:存储 存储器 系统地 何创建 创建 列表 唯一      更新时间:2023-09-26

我试图建立一个点击页面元素的历史列表,并将该列表存储到HTML本地存储中,稍后显示给用户。主要的先决条件是列表不能包含重复项,因此,例如,如果用户单击项目A,然后单击项目B,然后再次单击项目A,则只记录A和B。第三次点击不被记录,因为它不是唯一的。

我也使用persistent .js。

我注意到我能够命名存储并给它一个键,两者都存储在本地存储的真实键中,因此:myStorageName>myKey和我的值是我放在那里的任何东西。

是这样的。我知道你可以在那里存储字符串化的JSON,但我的列表是由简单的javascript变量一个一个地建立起来的。

我知道第一次点击该怎么做:

myStorageName.set(myKey, myCurrentElementId); // myCurrentElementId = this.id

现在在第二次点击,这是我开始卡住的地方。原来的变量值已经存储了,现在我想添加新的变量值。假设我可以像这样从存储中获取值:

var dataExtract = myStorageName.get(myKey);
myObject = JSON.parse(dataExtract);

但是我如何把它变成一个JSONstring -able thing(对不起,我甚至不知道它应该是什么),只包含一个唯一值的列表。有人能理解吗?

首先,您不希望每次单击链接时都向localStorage写入/从localStorage写入,因为这会减慢页面速度。用元素id填充一个更新的数组,然后在用户导航离开页面之前写入localStorage(例如,通过绑定到窗口的onbeforeunload事件)。

:

var clickedLinks = []; // this Array will hold the ids of the clicked links
function uniqueClick(id){
    return !~clickedLinks.indexOf(id); // this tests whether the id is already in the Array
};

在你的点击处理程序中:

if(uniqueClick(this.id)){
    clickedLinks.push(this.id); // append the new element id to the Array
}

绑定到window.onunload以在用户从页面导航之前保存Array:

window.onunload = function(){
    localStorage.setItem('clickedLinks',JSON.stringify(clickedLinks)); // stringify the Array and save to localStorage
}

在随后的页面访问中检索clicklinks:

// convert the String back to an Array; try/catch used here in case the value in localStorage is modified and unable to be parsed, in which case clickedLinks will be initialized to an empty Array
try{
    var clickedLinks = JSON.parse(localStorage.getItem('clickedLinks')) || [];
}catch(e){
    var clickedLinks = [];
}

你可能想用这最后一位代码替换第一行(var clickedLinks = [];),因为如果它不存在,它将初始化数组。


更新:

IE8不支持Array.indexOf。其他选项可能是:

  1. 使用jQuery的$。用!~$.inArray(id, clickedLinks);替换!~clickedLinks.indexOf(id);
  2. 检测是否支持Array.prototype.indexOf。如果没有,用本页提供的代码填充它。

您的模型出现错误。第一次,您保存一个原始值。然后,您想要向它"追加"另一个值。看起来你实际上想使用一个对象:

var myObj = localStorage.getItem("myName");
if(myObj) myObj = JSON.parse(myObj); //Variable exists
else myObj = {}; //Elsem create a new object
function appendNewValue(name, value){
    myObj[name] = value;
    localStorage.setItem("myName", JSON.stringify(myObj));
    /* Saves data immediately. Instead of saving every time, you can
       also add this persistence feature to the `(before)unload` handler. */
}

我建议在你的代码中这样定义:

localStorage.set= function(key,val)
{
  localStorage.setItem(JSON.stringify(val));
}
localStorage.get = function(key,defval)
{
  var val = localStorage.getItem(key);
  if( typeof val == "undefined" ) return defval;
  return JSON.parse(val);
}

并使用它们来代替get/setItem。他们会给你准备好使用的JS值,你可以用你需要的方式使用。