我有一个表单部分,人们可以在其中添加他们的电子邮件地址。
我有几个问题:
(1)在提交电子邮件地址时,页面会刷新(我知道如果没有ajax或异步解决方案,这是不可避免的)。不过,这会引起第二个问题,
(2)我似乎无法将这些电子邮件保存为数组,并使用JSON.parse(localStorage.getItem('EmailsStuff'))将其显示出来
我的JS/Jquery的一部分

var total = [];
                $(document).on("click", ":submit", function(e) {
                    var stuff = ($($email).val())
                    total = [JSON.stringify(stuff)];

                    localStorage.setItem('EmailsStuff', JSON.stringify(total));
            });

和html:
<form class="newsletter">

        <input type="email" value="" placeholder="Join Update List Here" class ="newsletter-email" />
        <input type="submit" value="Thanks!" class="newsletter-email" id="fast"/>
    </form>

如果我取样:
localStorage.setItem('sample',JSON.stringify(["bob", "susan", "rafiki"]);

因此读作
JSON.parse(localStorage.getItem('sample'));

最佳答案

您的电子邮件输入选择器似乎错误,请尝试将其更改为:

var stuff = $('#email').val();

输入一个id:
<input id="email" type="email" value="" placeholder="Join Update List Here" class ="newsletter-email" />

看这个小提琴:https://jsfiddle.net/m8w1uaso/
编辑:
如果要保留以前输入的所有电子邮件地址,并在每次提交表单时将其添加到此数组中,可以执行以下操作:
$(document).on("click", ":submit", function(e) {
  var stuff = ($('#email').val());
    // Load emails
  var emails = JSON.parse(localStorage.getItem('EmailsStuff'));
  if (emails) {
    // If the item exists in local storage push the new email address to the array and and save
    emails.push(stuff);
    localStorage.setItem('EmailsStuff', JSON.stringify(emails));
  } else {
    // If the item doesn't exist in local storage set the item to a new array containing new email address
    localStorage.setItem('EmailsStuff', JSON.stringify([stuff]));
  }
});

$(document).on("click", "#loadEmail", function(e) {
  alert(JSON.parse(localStorage.getItem('EmailsStuff')));
});

看这个小提琴:https://jsfiddle.net/v9c6xnmh/

10-04 22:17
查看更多