let toDos = [
{
id: Date.now(),
toDo: "장보기"
},
{
id: Date.now(),
toDo: "청소하기"
}
]
function handleTodoSubmit (e) {
e.preventDefault();
const newToDo = toDoFormInput.value;
toDoFormInput.value = "";
const newToDoObj = {
text: newToDo,
id: Date.now(),
}
toDos.push(newToDoObj);
paintToDo(newToDoObj);
saveTodos();
}
function paintToDo (newToDo) {
const li = document.createElement("li");
li.id = newToDo.id;
const span = document.createElement("span");
span.innerText = newToDo.text;
const button = document.createElement("button");
button.innerText = "❌";
button.addEventListener("click", deleteToDo);
li.appendChild(span);
li.appendChild(button);
toDoList.appendChild(li);
}
결과:
다음 포스팅에서 x버튼이 클릭된 HTML의 id 값을 이용해
로컬스토리지에서 해당 아이템을 삭제 하는 작업을 해야한다!
현재까지 작성된 코드:
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Momentum App</title>
<link rel="stylesheet" href="CSS/style.css">
</head>
<body>
<form id="login-form" class="hidden">
<input
required
maxlength="10"
type="text"
placeholder="What is your name?" />
<input type="submit" value="Log In" />
</form>
<h2 id="clock">00:00</h2>
<h1 id="greeting" class="hidden"></h1>
<form id="todo-form">
<input type="text" placeholder="Write a To Do and Press Enter" required/>
</form>
<ul id="todo-list"></ul>
<div id="quotes">
<span></span><br/>
<span></span>
</div>
<script src="JS/greetings.js"></script>
<script src="JS/clock.js"></script>
<script src="JS/Quotes.js"></script>
<script src="JS/background.js"></script>
<script src="JS/todo.js"></script>
</body>
</html>
const toDoForm = document.querySelector("#todo-form");
const toDoList = document.querySelector("#todo-list");
const toDoFormInput = toDoForm.querySelector("input");
const TODOS_KEY = "todos";
let toDos = [];
function saveTodos () {
localStorage.setItem(TODOS_KEY, JSON.stringify(toDos));
}
function deleteToDo(e) {
const li = e.target.parentElement;
li.remove();
}
function paintToDo (newToDo) {
const li = document.createElement("li");
li.id = newToDo.id;
const span = document.createElement("span");
span.innerText = newToDo.text;
const button = document.createElement("button");
button.innerText = "❌";
button.addEventListener("click", deleteToDo);
li.appendChild(span);
li.appendChild(button);
toDoList.appendChild(li);
}
function handleTodoSubmit (e) {
e.preventDefault();
const newToDo = toDoFormInput.value;
toDoFormInput.value = "";
const newToDoObj = {
text: newToDo,
id: Date.now(),
}
toDos.push(newToDoObj);
paintToDo(newToDoObj);
saveTodos();
}
toDoForm.addEventListener("submit", handleTodoSubmit);
const savedToDos = localStorage.getItem(TODOS_KEY);
if (savedToDos !== null) {
const parseToDos = JSON.parse(savedToDos);
console.log(typeof parseToDos);
toDos = parseToDos;
parseToDos.forEach(paintToDo);
}