ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [TIL] 0112
    카테고리 없음 2024. 1. 12. 21:29

     

    const form = document.querySelector("form");
    const input = document.querySelector("input");
    const ul = document.querySelector("ul");

    let inputUserInfos = [];  //전체 아이템을 저장할 배열

    const save = () => {
    localStorage.setItem("inputUserInfos", JSON.stringify(inputUserInfos));
    };

    const delItem = () => {
    const target = event.target.parentElement;
    inputUserInfos = inputUserInfos.filter(
    (inputUserInfo) => inputUserInfo.id !== parseInt(target.id)
    );
    save();

    target.remove();
    };

    const addItem = (inputUserInfo) => {
    if (inputUserInfo.text !== "") {
    const li = document.createElement("li");
    const button = document.createElement("button");
    const span = document.createElement("span");

    span.innerText = "inputUserInfo.text";
    button.innerText = "삭제";
    button.addEventListener("click", delItem);

    li.appendChild(button);
    li.appendChild(span);
    ul.appendChild(li);
    li.id = inputUserInfo.id;
    }
    };

    const handler = (event) => {
    event.preventDefault();

    const inputUserInfo = {
    id: Date.now(),
    text: input.value,
    };

    inputUserInfos.push(inputUserInfo);
    addItem(inputUserInfo);
    save();
    input.value = ""; //인풋창 초기화
    };
    // 폼이 제출될 때 (submit 이벤트 가 일어날때) 페이지 새로고침 되지 않도록

    const init = () => {
    const initInputUserInfo = JSON.parse(localStorage.getItem("inputUserInfos"));

    if (initInputUserInfo) {
    initInputUserInfo.forEach((inputUserInfo) => {
    addItem(inputUserInfo);
    });

    inputUserInfos = initInputUserInfo;
    }
    };

    init();
    form.addEventListener("submit", handler);
Designed by Tistory. KYW