javascript - 在 localStorage 中保存待办事项

标签 javascript local-storage

我创建了一个待办事项应用程序,我想将待办事项保存在 localStorage 中.
我正在考虑添加 localStorage像这样的属性(property):

addForm.addEventListener("submit", (e) => {
    e.preventDefault();
    let todo = addForm.add.value.trim();
    if (todo.length) {
        localStorage.setItem(todo);
        generateTemplate(todo);
        addForm.reset();
    }
}
但是,它不起作用。
所以,我的问题是,最好在代码的哪一部分添加属性,在哪一部分添加 getItem 是最好的。方法?

这是没有 localStorage 的完整代码属性(property):

const addForm = document.querySelector(".add");
const list = document.querySelector(".todos");
const search = document.querySelector(".search input");

// generate new toDo's
const generateTemplate = (todo) => {
  let html = ` <li class="list-group-item d-flex justify-content-between align-items-center">
    <span>${todo}</span><i class="far fa-trash-alt delete"></i>
  </li>`;
  list.innerHTML += html;
};

// submit the todo
addForm.addEventListener("submit", (e) => {
  e.preventDefault();
  let todo = addForm.add.value.trim();
  if (todo.length) {
    generateTemplate(todo);
    addForm.reset();
  }
});

// delete todo's

list.addEventListener("click", (e) => {
  if (e.target.classList.contains("delete")) {
    e.target.parentElement.remove();
  }
});

// filter the toDo's

const filterTodos = (term) => {
  Array.from(list.children)
    .filter((todo) => !todo.textContent.toLowerCase().includes(term))
    .forEach((todo) => todo.classList.add("filtered"));

  Array.from(list.children)
    .filter((todo) => todo.textContent.toLowerCase().includes(term))
    .forEach((todo) => todo.classList.remove("filtered"));
};

search.addEventListener("keyup", () => {
  const term = search.value.trim().toLowerCase();
  filterTodos(term);
});
body {
  background-color: #352f5b;
}

.container {
  max-width: 400px;
}

input[type="text"],
input[type="text"]:focus {
  color: #fff;
  border: none;
  background: rgba(0, 0, 0, 0.2);
  max-width: 400px;
}

.todos li {
  background: #423a6f;
}

.delete {
  cursor: pointer;
}

.filtered {
  display: none !important;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>toDoList</title>
  <script src="https://kit.fontawesome.com/fa5117c01c.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" />
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <header class="text-center text-light my-4">
      <h1 class="text-ligth mb.4">thingsToDo</h1>
      <form action="" class="search"><input type="text" class="form-control m-auto" name="search" placeholder="Search toDo's"></form>
    </header>
    <ul class="list-group todos mx-auto text-light"></ul>
    <form class="add text-center my-4">
      <label class="text-light">Add new toDo...</label>
      <input type="text" class="form-control m-auto" name="add">
    </form>
  </div>
  <script src="index.js"></script>
</body>

</html>

最佳答案

Storages 对象(与 LocalStorage 一起使用的对象)允许保存字符串(具体为 DOMStrings),因此如果要保存 javascript 对象,应先将其转换为字符串(例如使用 JSON.stringify )
在您的代码中,setItem 的语法也是如此。是不正确的。您需要指定 a key that identifies the object

   localStorage.setItem('todo', todo);
请注意,这只会保存一个待办事项。因此,当您收到待办事项时,您需要执行 localStorage.getItem('todo')这当然只会返回您保存的最后一个待办事项。
对此的解决方案可能是为您的待办事项提供存储:
var todos = []
每次创建新的待办事项时,您都会将该待办事项添加到该对象
todos.push(todo)
并将其保存到本地存储
localStorage.setItem('todos', JSON.stringify(todos))
当您取回该列表时,您将需要 parse返回字符串以获取实际对象:
var todosString = localStorage.getItem('todos');
var todos = JSON.parse(todosString);
考虑到这只会将您的 todos 数据放入该 var。然后你需要重新填充你的 dom。
这可以通过重复使用您的 generateTemplate 来完成。功能。
例如。
todos.forEach(todo => generateTemplate(todo));
我还建议您查看 LocalStorage 的 MDN 页面:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
完整的工作示例的使用 Web 存储 API 页面:https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

关于javascript - 在 localStorage 中保存待办事项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63839805/

相关文章:

javascript - 在 cshtml 中的迭代表上设置 ng-bind-html

使用 For 和 While 循环将 JavaScript 控制台输出到单行

JavaScript 可以正常工作,直到我添加此 && 语句。

jquery - Localstorage to JSON : How can I delete only 1 array inside a key since localstorage. remove Item 需要整个key

javascript - 从子域访问根域的 localStorage

java - 如何在java小程序中使用html5本地存储?

javascript - 按 HTML 数据属性对数组进行排序?

javascript - SlikGrid 虚拟滚动 - 巨大的数据集

javascript - 如何使用ionic cordova app加密设备上的本地表单数据

javascript - 如何使用 Google Visualization Query 搜索电子表格