자바스크립트로 해결하기

 

 

업데이트는 id가 필요하다.

 

 

 

[ ReplyController]

: id가 없는 경우 reply에 id가 있어서

@PutMapping
public ReplyVO replyUpdatePUT(@RequestBody ReplyVO reply) {
    replyService.modify(reply); //DB에 댓글 수정하기
    return reply;	//테스트로 reply 리턴
}

 

 

수정버튼 클릭했을때 updateReply 함수가 실행 
this는? 여러 댓글 중에 내가 누른 댓글의 수정버튼 (본인의 객체를 변수로)

onclick="updateReply(this)" data-id="${id}"
let li =
    `<li class="list-group-item" style="position: relative">
        <div>${writer}  ( ${updateTime} ) </div>
        <p class="mb-0">${content}</p>
        <textarea class="w-100" style="display:none">${content}</textarea>
        <div style="position: absolute; top: 10px; right: 10px">
            <button onclick="updateReply(this)" data-id="${id}" 
                        class="badge bg-gradient-info ms-auto">수정</button>
            <button class="badge bg-gradient-danger">삭제</button>
        </div>
    </li>`;

 

 

 

updateReply  함수만들어준다

function updateReply(elem){
     //console.log(elem);  //해당 수정버튼이 눌러지는지 테스트
    const 댓글내용 = el.parentElement.previousElementSibling.previousElementSibling;
    const 댓글수정 = el.parentElement.previousElementSibling;   //수정 할 수있는 textarea 창
    const 댓글삭제 = el.nextElementSibling;

   if(el.textContent === '수정'){   //버튼 이름이 '수정'
      댓글내용.style.display = 'none';
      댓글수정.style.display = 'block';  //보이도록
      댓글삭제.style.visibility = 'hidden';  //완전히 삭제가 아니라 잠깐 숨김
    }
}

※ 객체를 선택할때는 const

 

수정버튼을 누르면 textarea창이 보이고 댓글내용은 숨김.

 

parentElement : 부모 태그
nextElementSibling  : 다음 태그
previousElementSibling  : 이전 태그

 

parentElement를 알려면 console에다가 적기

const 태그 = document.querySelector('button.badge') → 수정버튼
태그.parentElement   수정버튼의 부모태그 (한 개의 댓글 태그들)
태그.parentElement.parentElement    부모의 부모태그

 

태그.nextElementSibling   수정버튼 옆의 삭제버튼
태그.nextElementSibling.previousElementSibling   옆 삭제버튼에서 다시 수정버튼
태그.parentElement.previousElementSibling.previousElementSibling   댓글내용

 

 

 

수정완료 버튼을 눌렀을때

if(el.textContent === '수정'){ //버튼 이름이 '수정'
    댓글내용.style.display = 'none';
    댓글수정.style.display = 'block'; //보이도록
    삭제버튼.style.visibility = 'hidden'; //완전히 삭제가 아니라 잠깐 숨김
    el.textContent = '수정완료';
} else {   //수정완료 버튼 눌렀을때 서버로 update 요청
    const data = {
        reply_no: el.dataset.id,
        content:댓글수정.value
   
      http    
         .put('/reply',data)
         .then((res) => 댓글내용.textContent = res.content)
         .catch((err) => replyListView(err));

      댓글내용.style.display = 'block';
      댓글수정.style.display = 'none'; //보이도록
      댓글삭제.style.visibility = 'visible';
      el.textContent = '수정';

    };
}

 

수정버튼 클릭시 썼던 data-id 는 data-[이름]

onclick="updateReply(this)" data-id="${id}"

data-id = dataset.id  

 

 

 

 

반응형
LIST

+ Recent posts