将每个新字符串保存到本地存储中的数组中
Saving Every new String in to an array in Local Storage
我试图保存每一个新的字符串,我收到(结果)从输入到一个数组在本地存储,以后使用它
$('.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>");
}
});
});
相关文章:
- Meteor会话变量未存储数组
- 在Javascript的Textbox中存储数组中的值
- 如何保留输入复选框值的存储数组
- 如何在 localStorage 中存储数组
- 如何在打包的 chrome 应用中本地存储数组
- 如何在 html5 的本地存储对象中存储数组
- 需要循环访问 json 数据的本地存储数组中存储的 json 对象
- 在 Javascript 中创建存储数组,并在每次单击时推送元素 ID
- 根据选中的复选框存储数组元素
- 如何存储数组javascript
- 存储数组在Chrome扩展
- 什么是最有效的方式来存储数组从PHP到JS/jQuery,这样它是可重用的
- Javascript存储数组值
- 存储数组到Cookie Jquery
- Ruby在遍历函数时尝试存储数组元素
- 如何从mongodb的形式存储数组
- 如何在html中打印存储在本地存储数组中的值
- 使用Firebase存储数组
- 获取字符串格式的MySQL存储数组并转换为JSON对象的数组
- 在html attr中存储数组值的最佳实践