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

change upยท2023๋…„ 6์›” 19์ผ
1
post-custom-banner
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;
toDos = toDos.filter(toDo => toDo.id !== parseInt(li.id));
saveToDos();
li.remove();
}
//toDo.id !== parseInt(li.id) ํƒ€์ž…์ด ๋‹ฌ๋ผ์„œ ์ž‘๋™์ด ์ œ๋Œ€๋กœ ํ•˜์ง€์•Š์•„ ๊ฐ™์€ ๋„˜๋ฒ„ํƒ€์ž…์œผ๋กœ ๋ณ€๊ฒฝ 
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)
    
}
/* ์‚ญ์ œ๊ธฐ๋Šฅ๋„ ๊ฐ€๋Šฅํ•˜๋„๋ก:span์„ ๋งŒ๋“ค์–ด์„œ li ๋‚ด๋ถ€์— ์ž์‹์œผ๋กœ ๋„ฃ์Œ ๊ทธ ๋‹ค์Œ์— new ToDo์— ์ž…๋ ฅ๋ฐ›์€ ๊ฐ’์„ span๋‚ด๋ถ€์— ๋„ฃ์Œ */

function handleToDoSubmit(event) {
    event.preventDefault();
const newTodo = toDoInput.value;
toDoInput.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 parsedToDos = JSON.parse(savedToDos);
    toDos = parsedToDos;
    parsedToDos.forEach(paintToDo);

}
//JS๋Š” ๋ฐฐ์—ด์— ์žˆ๋Š” ๊ฐ๊ฐ์˜ ์•„์ดํ…œ๋“ค์— ๋Œ€ํ•ด functioํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.
//toDoInput.value = "";(enter ํžˆ๋ฉด ์นธ์„ ๋นˆํ™”๋ฉด์œผ๋กœ ๋น„์šฐ๋„๋ก ๋งŒ๋“ ๋‹ค.)
//filter function -> new array
/* const arr = [1,2,3,4]
   arr.filter(item => item > 2 )
   [3,4] 
   const newArr = arr.filter (item =>item >2 )
   arr 
   [1,2,3,,4]
   newArr 
   [3,4]
   ๊ธฐ์กด์˜ ๋ฐฐ์—ด์„ ๋ณ€๊ฒฝ์‹œํ‚ค๋Š”๊ฒƒ์ด ์•„๋‹ˆ๋ผ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด๋ƒ„.*/
profile
์ƒˆ์‹น์ด
post-custom-banner

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