我正在尝试将从输入接收到的每个新字符串(结果)保存到本地存储中的数组中,以便稍后使用
$('.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>");
}
关于javascript - 将每个新字符串保存到本地存储中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530341/