login 페이지를 무사히 넘기고 main 페이지 구현에 들어갔다.
- 댓글 입력 후 엔터키를 누르거나 게시 버튼 클릭 시 댓글이 추가될 수 있도록 구현해주세요
👉 게시 버튼이 비활성화 되어있다.
👉 input에 값을 넣으면 게시 버튼이 활성화가 되어 진한 파랑색으로 바뀐다.
👉 엔터 or 클릭을 하면 댓글이 올라가며 게시 버튼은 다시 비활성화 된다.
Self Refactoring도 아직 하지 않은 날 것의 코드이다. 추후에 정리하고 비교해보자 🤗
const thisIsComment = document.querySelector('.comment_box');
const thisIsButton = document.getElementsByClassName('comment_submit')[0];
const thisIsNew = document.getElementsByClassName('newcomment')[0];
thisIsComment.addEventListener('keyup',buttonOn)
function buttonOn(e){
let a = thisIsComment.value
if(a){
thisIsButton.disabled = false;
thisIsButton.style.opacity = 1;
} else {
thisIsButton.disabled = true;
thisIsButton.style.opacity = .4;
}
if (thisIsButton.disabled==false && e.code == 'Enter') {
enterPost();
}
};
thisIsButton.addEventListener('click', enterPost)
function enterPost(){
if(thisIsComment.value){
const newUser = document.createElement('span');
newUser.className = "userid";
newUser.innerText = "k_rystalee";
const newComment = document.createElement('span');
newComment.className = "commentbox";
newComment.appendChild(newUser);
newComment.innerHTML +=thisIsComment.value;
const newImg = document.createElement('img');
newImg.className = "comment_heart";
newImg.setAttribute('src','img/heart.png');
const newList = document.createElement('li')
newList.className = "newcommentlist";
newList.appendChild(newComment);
newList.appendChild(newImg);
thisIsNew.appendChild(newList);
thisIsComment.value = "";
thisIsButton.disabled = true;
thisIsButton.style.opacity = .4;
}
};
- createElement(a)-> a라는 element를 만들어준다
- a에 값을 넣어주고
- appenChild를 사용해 부모에 자식을 존속시킨다.
- if문을 사용해 버튼이 활성화되거나 e.code === enter을 사용하면 enterPost함수가 구현된다.
- thisIsComment.value = ""; 댓글을 달고 내용을 비워둔다.
js 하는데 createElement에 대해 이해가 전혀 안되서 엄청 애먹었다. 동기님의 반복된 학습으로 도움을 주셨고 같이 로직 고민을 해주셔서 정말 감사했다. 코드를 줄이기 위해 새로 짜보다가 엔터를 두 번 쳐야 게시가 비활성화 되는 문제도 겪었다. 문제를 해결하려 오랜 시간을 고민했는데 답은 마지막에 비활성화 로직을 구현하지 않아서 그랬다.엔터를 하면 다시 if(a)로 돌아가 활성화된 상태로 있어서 마지막에 비활성화 로직을 넣으면 해결된다~ 😆
👍🏼👍🏼👍🏼👍🏼👍🏼