将每个新字符串保存到本地存储中的数组中

Saving Every new String in to an array in Local Storage

本文关键字:存储 数组 字符串 保存      更新时间:2023-09-26

我试图保存每一个新的字符串,我收到(结果)从输入到一个数组在本地存储,以后使用它

                $('.crearGpo').on('click',function() {
            bootbox.prompt("Name of the Gr", function(result ,e) {
                if(result != null && result !="" )
                {
                    names = [];
                    names[0]= result;
                    localStorage["names"] = JSON.stringify(names);
                    var storedNames = JSON.parse(localStorage["names"]);
                    console.log(storedNames);
                    localStorage.setItem('name', result);
                    name = localStorage.getItem('name');
                   $('.top-card-grupos ul ').last().append("<li><button class='"btn'" id='""+name+"'">"+name+"</button></li>");

                }

            });
        });

但是只是保存最后一个字符串,而不是我收到的每个字符串,任何帮助将是伟大的

您为每个结果创建了一个新数组,而不是每次为其赋值时增加数组索引,这意味着每个值都将被覆盖。试一试:

names = []; //Array for all results
var count = 0; //Keep track of the number of results
if(result != null && result !="" )
            {
                names[count++]= result; //Store and increment counter
                localStorage["names"] = JSON.stringify(names);
                var storedNames = JSON.parse(localStorage["names"]);
                console.log(storedNames);
                localStorage.setItem('name', result);
                name = localStorage.getItem('name');
               $('.top-card-grupos ul ').last().append("<li><button class='"btn'" id='""+name+"'">"+name+"</button></li>");

            }

每次点击都创建一个新的数组。你应该创建它一次,并在每次点击时向其推送值。

:

var names = []; // create the array once
$('.crearGpo').on('click', function() {
  bootbox.prompt("Name of the Gr", function(result, e) {
    if (result != null && result != "") {
      names.push(result); //add the result to the names array
      localStorage["names"] = JSON.stringify(names);
      var storedNames = JSON.parse(localStorage["names"]);
      console.log(storedNames);
      localStorage.setItem('name', result);
      name = localStorage.getItem('name');
      $('.top-card-grupos ul ').last().append("<li><button class='"btn'" id='"" + name + "'">" + name + "</button></li>");
    }
  });
});