将用户输入存储到localStorage

问题描述 投票:2回答:2

您好我正在尝试了解本地存储的工作原理。我正在尝试接受用户输入并将其添加到本地存储。我不确定哪个参数我错了。这是我的代码:

const myForm = document.getElementById("todo");
const list = document.querySelector(".list-items");
myForm.addEventListener("submit", addTodo);

function addTodo(e) {
  e.preventDefault();
  const userInput = document.querySelector(".userAdd").value;
  const userListItem = document.createElement("li");
  userListItem.appendChild(document.createTextNode(userInput));
  list.appendChild(userListItem);
  localStorage.setItem('userListItem', userInput);
}
<form id="todo">
  <input class="userAdd" type="text">
  <input  type="submit">
</form>
<ul class="list-items"></ul>
javascript html local-storage
2个回答
1
投票

要在list items中保存你的localStorage,你需要将它们保存在array中。我相应地修改了你的代码。 https://codepen.io/dasseya1/pen/qMXQmK

const myForm = document.getElementById("todo");
const list = document.querySelector(".list-items");
myForm.addEventListener("submit", addTodo);

function addTodo(e) {
  e.preventDefault();
  const userInput = document.querySelector(".userAdd").value;
  const userListItem = document.createElement("li");
  userListItem.appendChild(document.createTextNode(userInput));
  list.appendChild(userListItem);
  const myArray = map(listItems, getText);
  localStorage.setItem('userListItem', JSON.stringify(myArray));
}

const listItems = document.getElementsByTagName('li');


function map(arrayLike, fn) {
    var ret = [], i = -1, len = arrayLike.length;
    while (++i < len) ret[i] = fn(arrayLike[i]);
    return ret;
}

function getText(node) {
    if (node.nodeType === 3) return node.data;
    var txt = '';
    if (node = node.firstChild) do {
        txt += getText(node);
    } while (node = node.nextSibling);
    return txt;
}
<form id="todo">
  <input class="userAdd" type="text">
  <input  type="submit">
</form>
<ul class="list-items"></ul>

0
投票

这完全没问题。当我刷新页面时,它仍然存在。在你的例如Chrome console中进行测试...此外,如果刷新页面后此代码消失,那么我建议检查您的浏览器Privacy settings希望它有所帮助。

想象一下这是你的userInput数据:

let userInput = ['one', 'two', 'three'];

// Check browser support
if (typeof(Storage) !== "undefined") {
    // Store - [ we would pass it like this, using -> JSON.stringify ]
    localStorage.setItem("userListItems", JSON.stringify(userInput)); 
} else {
    console.warn("Sorry, your browser does not support Web Storage...");
}

// Retrieve - and when we want to get the item we would use JSON.parse to give us back an array
console.log(JSON.parse(localStorage.getItem("userListItems")));

旁注:如果你正在使用Chrome(我希望你这样做),你可以按CTRL + SHIFT + I转到你的'Application'标签,然后在'Storage'下点击'Local Storage' ...你会在那里找到你的数据并进一步检查它。

更新:感谢@Kaiido,我已经将我的答案更新为更好的版本 localStorage只存储字符串。所以在我之前的回答中,它会被强制给"one, two, three",但现在你真的得到了array

© www.soinside.com 2019 - 2024. All rights reserved.