ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 23.06.06) LocalStorage를 이용한 데이터 저장 (2)
    썽이의 개발 일지/TIL 2023. 6. 6. 17:57

    💻코드 리뷰하기

    🔻JS -  각 댓글마다  <div> 요소를 생성하고, 그 안에 <span> 요소를 추가하여 댓글 내용을 표시하는 부분

    // 댓글을 HTML에 추가
      comments.forEach(function (comment, index) {
        let commentElement = document.createElement("div"); // 각 댓글 요소를 생성
        commentElement.classList.add("comment"); // "comment" 클래스 추가(css 추가용)
    
        let commentText = document.createElement("span"); // <div> 요소에 댓글내용 <span>요소를 자식으로 추가)
        commentText.innerHTML = "<b>" + comment.name + "</b> : " + comment.comment;

     

    1. commentElement 요소에 classList.add메서드를 사용하여 "comment" 클래스를 추가

         => css 스타일링을 적용하기 위함

     

    2. span 요소를 생성하여 commentText 변수에 할당 (댓글 내용을 표시하기 위한 요소)

    3. commentText 요소의 innerHTML 속성을 설정해서 댓글 내용을 HTML 형식으로 작성

     

    🔻JS - 댓글 수정 : Update (갱신) 

    // 댓글 수정 버튼 추가
        let editButton = document.createElement("button"); //댓글 수정 button 요소 생성
        editButton.innerHTML = "수정"; //버튼에 표시될 텍스트
        editButton.addEventListener("click", function () {
          let password = prompt("비밀번호를 입력하세요.");
    
          if (password !== null && password === comment.password) {
            let newComment = prompt(
              "수정할 댓글 내용을 입력하세요.",
              comment.comment
            );
            if (newComment !== null) {
              editComment(index, newComment); //index : 댓글 인덱스, newComment : 입력한 수정된 댓글 내용
            }
          } else {
            alert("비밀번호가 일치하지 않습니다.");
          }
        });
    // 댓글 수정 함수
    let editComment = (index, newComment) => {
    //로컬 스토리지에서 "comments" 키의 값 가져오기
      let comments = JSON.parse(localStorage.getItem("comments")) || [];
    
      comments[index].comment = newComment;
    
      localStorage.setItem("comments", JSON.stringify(comments));
      loadComments();
    };

    1. prompt 함수를 사용하여 수정 버튼 클릭 시 비밀번호를 입력하도록 요청

       - 입력된 비밀번호는 password 변수에 저장

     

    2. null이 아닌 경우와 입력한 비밀번호가 댓글의 비밀번호와 일치하는지 확인 후

       수정할 댓글 내용을 입력하도록 요청 (입력된 내용은 newComment 변수에 저장)

     

    3. 수정된 댓글 내용은 editComment 함수를 호출하여 처리

     

    4. localStorage.getItem("comments")를 사용 

       - 로컬 스토리지에서 "comments"라는 키의 값 가져온다.
       - 가져온 값은 JSON 형식의 문자열이기 때문에  JSON.parse()를 사용하여 JavaScript 객체로 변환
       - 만약 키의 값이 없거나 로컬 스토리지가 비어있는 경우, 빈 배열([ ])을 comments 변수에 할당

    5. comments[index].comment = newComment : 선택된 댓글의 내용을 수정된 내용으로 업데이트
       - comments 배열에서 index에 해당하는 댓글의 comment속성을 newComment로 수정

    6. localStorage.setItem()을 사용하여 수정된 댓글을 다시 로컬 스토리지에 저장
       - "comments"키로 comments배열을 다시 JSON 형식의 문자열(JSON.stringify)로 변환하여 저장

    7. loadComments() : 함수를 호출하여 수정된 댓글을 다시 로드

     

     

    🔻JS -  댓글 삭제 : Delete (삭제)

    // 댓글 삭제 버튼 추가
        let deleteButton = document.createElement("button");
        deleteButton.innerHTML = "삭제";
        deleteButton.addEventListener("click", function () {
          let password = prompt("비밀번호를 입력하세요.");
    
          if (password !== null && password === comment.password) {
            if (confirm("댓글을 삭제하시겠습니까?")) {
              deleteComment(index);
            }
          } else {
            alert("비밀번호가 일치하지 않습니다.");
          }
        });
    // 댓글 삭제 함수
    let deleteComment = (index) => { //삭제할 댓글의 인덱스
      let comments = JSON.parse(localStorage.getItem("comments")) || [];
    
      comments.splice(index, 1);
      localStorage.setItem("comments", JSON.stringify(comments));
      loadComments();
    };

    1. prompt 함수를 사용하여  비밀번호를 입력하도록 요청 (입력된 비밀번호는 password 변수에 저장)

     

    2. confirm 함수를 사용하여 댓글을 삭제할 것인지 확인

     

    3. deleteComment(index) 함수를 호출하여 댓글을 삭제

     

    4. comments.splice(index, 1) : splice() 메서드를 사용하여 배열 특정 위치의 요소를 제거
       - comments 배열에서 index 에 해당하는 댓글을 삭제
       - 1은 삭제할 요소의 개수

     

    📌참고자료

    *localStorage사용법 : https://hianna.tistory.com/697

    *classList (개인 프로젝트때도 참고했던 블로그)  :https://hyunjungchoi.tistory.com/70

    *splice() 메서드 : https://www.freecodecamp.org/korean/news/javascript-splice-method/

Designed by Tistory.