<인스타그램 클론코딩>
forEach문을 이용해 각각의 피드에서 댓글을 입력하고 엔터를 누르거나 게시버튼을 누르면 댓글이 등록되는 기능을 구현해보았습니다.😊
이 포스팅에서는 엔터를 누르면 등록될때의 코드만 다루고 있습니다.
이제 막 시작한 코린이라 코드가 깔끔하지 않을 수 있습니다.
피드백은 언제나 감사하게 받으니 오류나 개선점이 보인다면 꼭! 댓글부탁드립니다:D
만약 하나의 피드에만 댓글을 입력하고싶다면 forEach문으로
반복을 할 필요가 없습니다. 하지만 모든 피드에 댓글을 입력할 수 있게 하기위해 forEach문을 사용해보도록 하겠습니다.
✅주석없는 소스코드는 포스팅 맨 아래에 있습니다
// 1.자바스크립트로 필요한 요소들 불러오기
// 저는 댓글게시버튼에 class를 주지않아서 TagName으로 불러왔습니다
const commentWriteInput = document.getElementsByClassName("comment-input");
const commentWriteButton = document.getElementsByTagName("button");
const commentList = document.getElementsByClassName("commentList");
// 2.forEach문을 활용해 각각의 피드마다 댓글입력창 구현
Array.from(commentWriteInput).forEach((value, index) => {
//addEventListener로 키 입력 감지
commentWriteInput[index].addEventListener("keyup", (e) => {
// 입력된 키의 키코드가 13(=enter의 키코드)이고(AND)
// input창의 값이 있다면(true) 조건문 실행
if (e.keyCode === 13 && commentWriteInput[index].value) {
const li = document.createElement("li");
const commentUserId = document.createElement("div");//사용자이름
const div = document.createElement("div");//댓글 내용
li.classList.add("comment");//css
commentUserId.classList.add("feedTextId");//css
commentUserId.innerText = "kim_code";//아이디에 'kim_code' 할당
div.innerText = commentWriteInput[index].value;
//댓글 내용에 input에 입력된 값할당
div.classList.add("feedTextContent");//css
//li요소에 아이디와 댓글내용 넣고 댓글리스트에 li요소넣기
li.append(commentUserId,div);
commentList[index].appendChild(li);
//input값은 다시 비워주기
commentWriteInput[index].value = "";
}
});
});
이렇게 구현해보았습니다. forEach문을 이해하는데 많은 시간이 소요되었는데
그만큼 정확하게 이해한 것 같습니다 아마도...? 나중가면 더 깔끔하게 작성할 수 있지 않을까 싶네요 나중에 forEach문도 자세히 포스팅해보도록...
const commentWriteInput = document.getElementsByClassName("comment-input");
const commentWriteButton = document.getElementsByTagName("button");
const commentList = document.getElementsByClassName("commentList");
Array.from(commentWriteInput).forEach((value, index) => {
commentWriteInput[index].addEventListener("keyup", (e) => {
if (e.keyCode === 13 && commentWriteInput[index].value) {
const li = document.createElement("li");
const commentUserId = document.createElement("div");
const div = document.createElement("div");
li.classList.add("comment");
commentUserId.innerText = "kim_code";
commentUserId.classList.add("feedTextId");
if (commentWriteInput[index].value) {
div.innerText = commentWriteInput[index].value;
div.classList.add("feedTextContent");
}
li.appendChild(commentUserId);
li.appendChild(div);
commentList[index].appendChild(li);
commentWriteInput[index].value = "";
commentWriteButton[index].classList.remove("comment-btn");
commentWriteButton[index].disabled = true;
}
});
});