如何在待办事项应用程序中使用本地存储 (javascript)

how use localstorage in todo app (javascript)

如何在下面的代码中使用存储属性? 此代码无法正常工作并在每次刷新后消失。

请在下面的link中检查我的代码 https://jsfiddle.net/74qxgonh/

let values = [];

// TAG Form ( give text)
document.querySelector("form").addEventListener("submit", (e) => {
  e.preventDefault();

  // create object  (unique id)
  storageValue = {
    id: "num" + Math.floor(Math.random() * (1000, 9000)),
    text: e.target.elements.textInput.value,
  };

  //create Array for save to localStorage
  values.push({ storageValue });
  localStorage.setItem("values", JSON.stringify(values));
  
  //create Tags
  let input = document.createElement("input");
  input.setAttribute("type", "checkbox");
  input.setAttribute("class", "chk-box");
  input.setAttribute("id", `${storageValue.id}`);

  let label = document.createElement("label");
  label.textContent = `${storageValue.text}`;
  label.setAttribute("for", `${storageValue.id}`);
  label.setAttribute("class", "chk-label");

  const btnDeleted = document.createElement("button");
  btnDeleted.setAttribute("class", "btn-delete");
  btnDeleted.textContent = "X";
  btnDeleted.addEventListener("click", () => {
    div.remove();
  });

  const div = document.createElement("div");
  div.setAttribute("class", "inputGroup");
  div.appendChild(input);
  div.appendChild(label);
  div.appendChild(btnDeleted);

  document.querySelector(".container-center").appendChild(div);

  e.target.elements.textInput.value = "";
});

您可能只需要将脚本的第一行替换为 get 以前保存的来自 localStorage 的项目,而不是每次应用程序加载时都从一个空数组开始:

// before
let values = [];
// after
let values;

try {
  values = JSON.parse(localStorage.getItem('values')) ?? [];
}
catch {
  values = [];
}