保存并更新数组到本地存储JS

时间:2020-05-11 01:29:37

标签: javascript

我正在尝试将数组发送到本地存储,当我单击按钮并且输入具有值时,元素将被发送到本地存储中的数组,如下所示:

["info before reloading 1","info before reloading 2","info before reloading 3"]

如果我重新加载页面并在输入中写点东西,则删除数组中的所有元素,并使用我输入的新信息创建一个新数组

["new info 1","new info 2","new info 3"]

我该如何避免删除初始信息,而只是像这样更新并保存在本地存储中

 ["info before reloading 1","info before reloading 2","info before reloading 3", "new info 1","new info 2","new info 3"];

感谢您的帮助

var mydiv = document.querySelectorAll(".div_btn");
console.log(mydiv);

for(i=0; i<mydiv.length; i++){
   mydiv[i].addEventListener("click", function(){
      var parent = this.parentElement;
      console.log(parent.firstElementChild.innerHTML);
   });
}


var btn_local = document.getElementById("btn_local");
var user_name = document.getElementById("user_name");

var mi_array = []; 

btn_local.addEventListener("click", function(){
  var name_value =  user_name.value;
  if(name_value !== ""){

   mi_array.push(name_value);
   console.log(mi_array);

   var json_transform = JSON.stringify(mi_array);
   localStorage.setItem("usuarios", json_transform);
  }
})
 <input type="text" id="user_name" placeholder="ingrese su nombre">
    <button id="btn_local">Send array to local host</button>

1 个答案:

答案 0 :(得分:2)

将数据保存到localStorage时,必须首先使用localStorage获取localStorage.getItem数据。

如果存在数据,则将数据添加到mi_array,否则将数组保留为空。

在当前代码中,您将忽略旧数据,仅将数组替换为新数据

尝试一下。

var mydiv = document.querySelectorAll(".div_btn");
console.log(mydiv);
for (i = 0; i < mydiv.length; i++) {
    mydiv[i].addEventListener("click", function () {
        var parent = this.parentElement;
        console.log(parent.firstElementChild.innerHTML);
    });
}

var btn_local = document.getElementById("btn_local");
var user_name = document.getElementById("user_name");
var mi_array = [];
btn_local.addEventListener("click", function () {
    var name_value = user_name.value;
    if (name_value !== "") {
        // Get the data from localStorage
        let currentData = localStorage.getItem("usuarios");
        // Check the data if its not null
        mi_array = currentData ? JSON.parse(currentData) : [];
        mi_array.push(name_value);
        var json_transform = JSON.stringify(mi_array);
        localStorage.setItem("usuarios", json_transform);
    }
})