๐Ÿ‘ฉ๐Ÿผโ€๐Ÿ’ป๋ฐ”๋‹๋ผ JS๋กœ ํฌ๋กฌ ์•ฑ ๋งŒ๋“ค๊ธฐ :#7.3-7.5

change upยท2023๋…„ 6์›” 15์ผ
0
post-custom-banner
  • saving todos/ loading todos
    โœ”๏ธtoDos๋ฅผ JSON.stringify ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์žํ™” ํ•ด์„œ ์ €์žฅํ•˜๊ณ ,
    ์ €์žฅํ•œ ๋‚ด์šฉ์„ ๋‹ค์‹œ JSON.parse()๋กœ ๋ฐฐ์—ดํ™” ์‹œ์ผœ forEach ๋กœ
    ์ฃผ์–ด์ง„ ๋‚ด์šฉ์— ์ ‘๊ทผํ•  ์ˆ˜์žˆ๋„๋ก ํ•˜์—ฌ ๊ฐ๊ฐ์— ๋Œ€ํ•ด ์‹คํ–‰์‹œํ‚จ๋‹ค.
    ๊ฒฐ๊ณผ์ ์œผ๋กœ ์›นํŽ˜์ด์ง€๋ฅผ ์ƒˆ๋กœ๊ณ ์นจํ•˜์—ฌ๋„ ํ™”๋ฉด์ƒ์— todolist๊ฐ€ ํ‘œ์‹œ๋˜๊ณ 
    localstorage์— ์ €์žฅ๋˜์–ด ์žˆ๋‹ค.
const toDoForm = document.getElementById("todo-form");
const toDoInput = toDoForm.querySelector("input");
const toDolist = document.getElementById("todo-list");

const TODOS_KEY = "todos";

let toDos = [];

function saveToDos(){
    localStorage.setItem("TODOS_KEY", JSON.stringify(toDos))
}
//JSON.stringify: ์–ด๋–ค ๊ฒƒ์ด๋“  stringํ™” ์‹œ์ผœ์ค€๋‹ค.
//JSON.parse():string์„ ๋ฐฐ์—ด๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.

//event.target์„ ์‚ฌ์šฉํ•˜๋ฉด ํ˜„์žฌ ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•œ ์š”์†Œ์˜ ์†์„ฑ๋“ค์„ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.
//Dom ๊ฐ์ฒด์ด๊ธฐ ๋•Œ๋ฌธ์— ๋ณ€๊ฒฝ์„ ์ฃผ๊ณ  ์‹ถ๋‹ค๋ฉด Dom๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.
//button ์†์„ฑ์˜ ๋ถ€๋ชจ์š”์†Œ๋กœ li๋ฅผ ๊ฐ€๋ฅดํ‚จ๋‹ค.
function deleteToDo(event) {
const li = event.target.parentElement;
li.remove();
}

function paintToDo(newTodo) {
    const li = document.createElement("li");
    const span = document.createElement("span");
    span.innerText = newTodo;
    const button = document.createElement("button");
    button.innerText = "๐Ÿ™…๐Ÿป";
    button.addEventListener("click",deleteToDo)
    li.appendChild(span);
    li.appendChild(button);
    toDolist.appendChild(li)
    
}
/* ์‚ญ์ œ๊ธฐ๋Šฅ๋„ ๊ฐ€๋Šฅํ•˜๋„๋ก:span์„ ๋งŒ๋“ค์–ด์„œ li ๋‚ด๋ถ€์— ์ž์‹์œผ๋กœ ๋„ฃ์Œ ๊ทธ ๋‹ค์Œ์— new ToDo์— ์ž…๋ ฅ๋ฐ›์€ ๊ฐ’์„ span๋‚ด๋ถ€์— ๋„ฃ์Œ */

function handleToDoSubmit(event) {
    event.preventDefault();
const newTodo = toDoInput.value;
toDoInput.value = "";
toDos.push(newTodo);
paintToDo(newTodo)
saveToDos();
}

toDoForm.addEventListener("submit",handleToDoSubmit);


const savedToDos =localStorage.getItem(TODOS_KEY);

if(savedToDos !== null) {
    const parsedToDos = JSON.parse(savedToDos);
    toDos = parsedToDos;
    parsedToDos.forEach(paintToDo);

}
//JS๋Š” ๋ฐฐ์—ด์— ์žˆ๋Š” ๊ฐ๊ฐ์˜ ์•„์ดํ…œ๋“ค์— ๋Œ€ํ•ด functionํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.
//toDoInput.value = "";(enter ํžˆ๋ฉด ์นธ์„ ๋นˆํ™”๋ฉด์œผ๋กœ ๋น„์šฐ๋„๋ก ๋งŒ๋“ ๋‹ค.)
profile
์ƒˆ์‹น์ด
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€