繁体   English   中英

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

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

我正在尝试建立单击的单击页面元素的历史记录列表,并将该列表存储到HTML本地存储中,以便稍后显示给用户。 主要前提条件是列表不能包含重复项,例如,如果用户单击项目A,然后单击项目B,然后再次单击项目A,则仅记录A和B。 由于第三次单击不是唯一的,因此未记录。

我也在使用persist.js

我注意到,我能够命名存储并给它一个密钥,并且两者都一起存储在localstorage的真实密钥中: myStorageName>myKey而我的值就是我放在那的内容。

就是这个 我知道您可以在其中存储stringyfied JSON,但是我的列表是一次通过简单的JavaScript变量构建的。

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

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

现在,在第二次单击上,这就是我开始陷入困境的地方。 已经存储了原始变量值,现在我想追加新变量值。 假设我可以像这样从商店获得价值:

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

但是如何将其转换为仅包含唯一值列表的JSONstring 兼容的 thing (对不起,我什至不知道它应该是什么)。 这对任何人有意义吗?

首先,您不希望每次单击链接时都继续向localStorage写入数据,因为这会减慢您的页面速度。 保留一个填充有元素ID的更新后的Array,然后在用户离开页面之前(例如,通过绑定到窗口的onbeforeunload事件)将其写入localStorage。

第一:

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以在用户从页面导航之前保存阵列:

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

要在后续页面上检索clickedLinks,请访问:

// 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 = []; ),因为如果不存在,它将初始化Array。


更新:

IE8不支持Array.indexOf 替代方法可能是:

  1. 通过替换!~clickedLinks.indexOf(id); 〜clickedLinks.indexOf !~clickedLinks.indexOf(id);使用jQuery的$ .inArray !~clickedLinks.indexOf(id); !~$.inArray(id, clickedLinks);
  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值,您可以按需要使用它们。

暂无
暂无

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

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