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

标签 javascript html 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>");


            }

关于javascript - 将每个新字符串保存到本地存储中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530341/

相关文章:

javascript - 从同一方法中获取对象方法名称

html5 跨不同浏览器的本地存储

javascript - 如何保留同步期间发生的 DBChangeTracker 中的更改?

javascript - 无法将 socket.io 事件转换为 Bacon EventStream

javascript - 给 selector.method 作为参数,调用它

javascript - OSError : [WinError 193] %1 is not a valid Win32 application opencv. js

html - 在 div 之间应用空间

html - 如何垂直对齐 div 顶部的文本?

php - 表单操作和唯一 ID 有困难

mobile - localStorage 和替代方案的可靠性。 (适用于 iOS、Android、WP7、WP8 和黑莓的 PhoneGap)