JavaScript를 사용하여 localStorage에 데이터를 저장하는 방법

9367 단어 tutorialjavascript
이 자습서에서는 브라우저에서 저장소 개체에 액세스할 수 있도록 하는 창 인터페이스의 속성localStorage을 사용하는 방법을 배웁니다. localStorage 작동 방식에 대한 이해를 돕기 위해 localStorage 에서 데이터를 저장하고 삭제할 간단한 메모 작성 응용 프로그램을 빌드합니다.

새 메모를 추가하는 양식과 저장된 메모를 표시하는 정렬되지 않은 목록을 만들어 시작하겠습니다.

<form id="note-form">
  <input id="note-input" type="text" placeholder="+ Add Note" required />
  <button id="note-submit">Save</button>
</form>
<ul id="notes"></ul>


이제 JavaScript 기능을 위해 먼저 작업할 HTML 요소에 대한 변수를 선언합니다.

const noteForm = document.getElementById("note-form");
const noteInput = document.getElementById("note-input");
const noteSubmit = document.getElementById("note-submit");
const notes = document.getElementById("notes");


또한 기존 메모를 더 쉽게 작업할 수 있도록 noteStorage 변수에 저장합니다. localStorage에 메모가 없으면 아직 빈 배열만 있을 것입니다.

let notesStorage = localStorage.getItem("notes")
  ? JSON.parse(localStorage.getItem("notes"))
  : [];


다음으로 양식이 제출될 때 새 메모를 저장하는 기능을 추가합니다.

noteForm.addEventListener("submit", (e) => {
  e.preventDefault();
  notesStorage.push(noteInput.value);
  localStorage.setItem("notes", JSON.stringify(notesStorage));
  listBuilder(noteInput.value);
  noteInput.value = "";
});


이렇게 하면 새 메모가 notesStorage로 푸시된 다음 notes에서 localStorage가 업데이트됩니다. 그런 다음 HTML 마크업의 정렬되지 않은 목록 요소에 메모를 추가하는 listBuilder 함수를 호출합니다. 다음은 해당 함수에 대한 코드입니다.

const listBuilder = (text) => {
  const note = document.createElement("li");
  note.innerHTML = text + ' <button onclick="deleteNote(this)">x</button>';
  notes.appendChild(note);
};


메모는 이제 localStorage에 저장되고 HTML에 표시됩니다. 그러나 페이지를 새로 고치면 메모가 더 이상 HTML에 표시되지 않으므로 페이지가 로드될 때 localStorage의 각 메모를 반복하고 HTML에서 다시 렌더링해야 합니다.

const getNotes = JSON.parse(localStorage.getItem("notes"));
getNotes.forEach((note) => {
  listBuilder(note);
});


마지막으로 해야 할 일은 삭제 버튼에 대한 기능을 추가하는 것입니다.

const deleteNote = (btn) => {
  let el = btn.parentNode;
  const index = [...el.parentElement.children].indexOf(el);
  notesStorage.splice(index, 1);
  localStorage.setItem("notes", JSON.stringify(notesStorage));
  el.remove();
};


이것은 삭제할 목록 항목의 색인을 가져오고 HTML과 localStorage 모두에서 제거합니다.

이것이 이 튜토리얼의 전부입니다. localStorage 에서 데이터를 사용하는 방법에 대한 이해가 되었기를 바랍니다. 이 튜토리얼에 사용된 코드의 전체 작업 예제는 here 에서 다운로드할 수 있습니다.

좋은 웹페이지 즐겨찾기