将待办事项保存在localStorage中 [英] Save todos in localStorage

查看:46
本文介绍了将待办事项保存在localStorage中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个待办事项应用程序,我想将待办事项保存在 localStorage 中.

I've created a todo app, and I want to save the todo's in localStorage.

我当时正在考虑添加 localStorage 属性,如下所示:

I was thinking to add the localStorage property like this:

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

但是,它不起作用.

所以,我的问题是,最好在代码的哪一部分中添加属性,最好在哪一部分中还添加 getItem 方法?

So, my question is, in which part of the code is it best practice to add the property and in which part is it best to also add the getItem method?

这里是没有 localStorage 属性的整个代码:

Here is the whole code without the 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一起使用)允许保存字符串(特定于DOMString),因此,如果要保存javascript对象,则应转换它首先要字符串化(例如,使用 JSON.串化)

Storages object (what you use with LocalStorage) allows to save Strings (DOMStrings to be specific), so if you want to save a javascript object, you should convert it to string first (eg. with JSON.stringify)

在您的代码上, setItem 的语法也不正确.您需要指定识别对象的密钥

On your code, also, the syntax for setItem is incorrect. You need to specify a key that identifies the object

   localStorage.setItem('todo', todo);

请注意,这只会保存待办事项.因此,当您获得待办事项时,您将需要执行 localStorage.getItem('todo'),这当然只会返回您保存的最后一个待办事项.

Notice that this will only save a todo. Therefore, when you get todo's back you will need to do localStorage.getItem('todo') and this of course will only return the last todo that you have saved.

为此的一种解决方案可能是为您的待办事项存储空间:

A solution for this might be to have a storage for your todos:

var todos = []

每次创建新的待办事项时,都会将该待办事项添加到该对象中

Everytime you create a new todo you add that todo to this object

todos.push(todo)

并将其保存到本地存储

localStorage.setItem('todos', JSON.stringify(todos))

返回该列表时,您需要

When you get back that list, you will need to parse the string back to get the actual object:

var todosString = localStorage.getItem('todos');
var todos = JSON.parse(todosString);

请注意,这只会使您的待办事项数据进入该变量.然后,您需要重新填充您的dom.这可以通过重新使用您的 generateTemplate 函数来完成.例如

Take into account that this will only get your todos data into that var. Then you need to repopulate your dom. This can be done by reusing your generateTemplate function. Eg.

todos.forEach(todo => generateTemplate(todo));

我还建议您查看LocalStorage的MDN页面: https://developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage

I'd also recommend you to take a look at the MDN page for LocalStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

以及使用Web存储API"页面中的完整示例:

And the Using the Web Storage API page for a full working example: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

这篇关于将待办事项保存在localStorage中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆