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 에서 다운로드할 수 있습니다.
Reference
이 문제에 관하여(JavaScript를 사용하여 localStorage에 데이터를 저장하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/michaelburrows/how-to-save-data-in-localstorage-using-javascript-994텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)