我有一个表单部分,人们可以在其中添加他们的电子邮件地址。
我有几个问题:
(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" />
看到这个 fiddle :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')));
});
看到这个 fiddle :https://jsfiddle.net/v9c6xnmh/
关于javascript - 将 HTML 表单数据保存到本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39048661/