Javascript

Javascript CRUD를 활용한 댓글게시판을 만들어보자

개발적금 2022. 11. 15. 18:47

안녕하세요 개발적금입니다.

오늘은 CRUD를 활용하여

댓글을 작성할수있는 게시판?을 구현해보겠습니다.

총 2번으로 나뉘어서 구현을 할것이고

이번페이지에서는 CRUD중 Create / Read까지 해보겠습니다.

 

 


목차

 

1.CRUD에 대해

 

2. 작업순서

 

3. 코드내용리뷰


 

1. CRUD에 대해

 

CRUD란 단어의 앞자리들을 따서 부르는것인데,

 

Create - 데이터를 '입력'하고

 

Read - 데이터를 '볼수'있고

 

Update - 데이터를 '수정'할수있고

 

Delete - 데이터를 '삭제'할수있다. 입니다.

 

보통 작업을 할때에는 'Create'를 먼저 작업하는데, 'Create'작업은

'Read'와 연관성이 높습니다.

Create부분에서는 데이터를 어떻게 입력(저장)하는데 까지입니다!

 

그다음 'Read'는 데이터를 어떻게 보여주느냐? 입니다.

댓글 게시판으로 예를들면 Create부분은 댓글을 입력하고 등록버튼까지가 

Create일것이고, 그 댓글(데이터)을 보여주는부분이 Read일것입니다.

 


2. 작업순서

 

저는 Create부분을 먼저 처리를 할것입니다.

 

2.1  먼저 댓글 입력폼에 내용을 입력한 뒤, 'submit'을 누르면 리스트에 추가가 됩니다. 

2.2 만약 입력폼에 내용이 없는데 'submit'을 누르면, 경고창이 뜨게할것입니다.

2.3 댓글 입력이 성공적으로 처리가 되면 , 데이터를 저장시키고 , 입력Form에 남아있는

       데이터를 'reset'시킵니다.


다음은 Read부분입니다.

 

2.1 댓글 내용은 "아이디" , "댓글내용" , "날짜"를 표현할것입니다.

2.2 댓글 List는 최신순으로 표현할것입니다.


 

3. 코드내용리뷰

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
    <link rel="stylesheet" href="./public/css/index.css">
</head>
<body>
    <div>
        <ul class="comment">
            <li class = "comment-form">
                <form id = "commentFrm">
                    <h4>
                        댓글쓰기
                        <span></span>
                    </h4>
                    <span class="psbox">
                        <input type="text" placeholder="댓글 내용을 입력해주세요" class="int" name="content">
                    </span>
                    <input type="submit" class="btn" value="등록">
                </form>
            </li>

            <li id="comment-list">
                <!-- <ul class="comment-row">
                    <li class="commnet-id">web77722</li>
                    <li class="comment-content">내용!!</li>
                    <li class="comment-date">2022-11-15</li>
                     </ul> -->
            </li>
        </ul>
    </div>


    <script src="./public/js/index.js"></script>
</body>
</html>

 

우선 HTML부터 리뷰하겠습니다. 간단하게 생각하시면됩니다.

div 안에 ul태그(class="comment")를 사용하여 그밑에 댓글 폼을(class = "comment-form")를 만들었습니다.

 

그리고 그 밑에 li태그(id="comment-list")는 제가 댓글을 입력하면 , 데이터를 받아 실제로 추가될부분입니다.

 


CSS파일은 꾸밈의 용도로만 사용하였으니 구경만 해주시면 될것같습니다.

 

* {
    margin: 0;
    padding: 0;
}

ul,
li {
    list-style: none;
}

.comment {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    padding: 30px;
    width: 600px;
    margin: 0 auto;
}

.comment > li {
    margin-top: 20px;
}
.comment > li:nth-child(1) {
    margin: 0px;
}

.comment-row {
    display: flex;
    justify-content: space-between;
    flex-direction: row;
}

.comment-row {
    margin-top: 20px;
    width: 100%;
}

.comment-row > li:nth-child(2) {
    flex-shrink: 0;
    flex-grow: 1;
    padding-left: 25px;
    z-index: 1;
    width: 100%;
}

.comment-row > li:nth-child(2) {
    width: 85px;
}

.comment-form > form {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
}

.comment-form > form > h4 {
    width: 100%;
    margin: 14px 0 14px 0;
}

.comment-content {
    word-break: break-all;
    padding-right: 25px;
}

.ps_box {
    display: block;
    position: relative;
    width: 80%;
    height: 51px;
    border: solid 1px #dadada;
    padding: 10px 14px 10px 14px;
    background: #fff;
    box-sizing: border-box;
}

.ps_box > input {
    outline: none;
}

.int {
    display: block;
    position: relative;
    width: 100%;
    height: 29px;
    padding-right: 25px;
    line-height: 29px;
    border: none;
    background: #fff;
    font-size: 15px;
    box-sizing: border-box;
    z-index: 10;
}

.btn {
    width: 18%;
    padding: 18px 0 16px;
    text-align: center;
    box-sizing: border-box;
    text-decoration: none;
    border: none;
    background: #333;
    color: #fff;
    font-size: 14px;
}

.comment-delete-btn {
    display: inline-block;
    margin-left: 7px;
    cursor: pointer;
}

.comment-update-input {
    border: none;
    border-bottom: 1px solid #333;
    font-size: 16px;
    color: #666;
    outline: none;
}

 


const form = document.querySelector("#commentFrm");
const commentList = document.querySelector("#comment-list");
const list = [];


function Comment(content) {
    this.userid = "develop"
    this.content = content
    this.date = "2022-11-15"
}


function submitHandler(e){
    e.preventDefault();
    const input = e.target.content   

    if(input.value === ""){
        alert("내용을 입력하세요!");
        return;
    }

    const instance = new Comment(input.value);
    list.push(instance);
    drawing();
    e.target.reset(); 
    
}

function createRow(userid,content,date){
    const ul = document.createElement("ul");
    const li1 = document.createElement("li");
    const li2 = document.createElement("li");
    const li3 = document.createElement("li");

    ul.append(li1); 
    ul.append(li2);
    ul.append(li3);


    ul.setAttribute("class","comment-row")
    li1.setAttribute("class" , "comment-id");
    li2.setAttribute("class", "comment-content");
    li3.setAttribute("class", "comment-date");

    li1.innerHTML = userid;
    li2.innerHTML = content;
    li3.innerHTML = date;

    return ul;
}



function drawing(){
    commentList.innerHTML = "";
    for(let i = 0 ; i < list.length ; i++){
        // console.log(list[i].userid,list[i].content,list[i].date);
        const row = createRow(list[i].userid,list[i].content,list[i].date);
        commentList.append(row);
    }
}

form.addEventListener("submit",submitHandler);

 

Javascript 의 코드입니다.

 

1. Javascript에서 사용할 Element들을 가져오는 작업을 하였습니다

 

-> commentFrm(Form태그) , h4 > span(총 댓글의 수를 체크) , comment-list(댓글을 추가할때 들어가는공간?)

 

2. submit 이벤트가 발생하였을때에 작업을 하였습니다

 

form.addEventListener("submit",submitHandler);

-> submit 이벤트가 발생하였을시 , submitHandler 함수를 호출합니다.

 

3. function submitHandler(e){} 안에서 세부작업

 

-> submit이 작동하면 , 페이지를 이동시켜주기때문에(값을 전달하여 action=""로 이동함)

-> e.preventDefault() 메소드를 사용하여 이벤트의 작동을 잠시 멈추었습니다.

-> e.target.content를 사용하여 e.target(form태그입니다) form태그 안에 content값(input의 name속성)을 가져옵니다

-> const input = e.target.content / 값을 input 변수에 저장하고 , 조건문을 사용하여

-> 내용이 "" 빈칸이면 alert()을 통해 경고창을 띄어주었고 , return을 사용해 조건문을 빠져나왔습니다.


-> const instance = new Comment(input.value); >> instance변수에 생성자함수를 만들었고,

-> 인자값으로 input.value(작성한 댓글의 내용)을 넣었습니다.


3.1

function Comment(content){

 this.userid = "develop"

 this.content = content

 this.date = "2022-11-15"

}

-> 생성자 함수를 만들어 값을 넣어줍니다. CRUD를 처음써서 , 오늘은 내용만을 전달받아 객체를

만들겠습니다.

 


-> 생성자 함수를 통하여 값을 instance에 대입하였습니다.(1번째 댓글의 아이디,내용,날짜)

-> list.push(instance) >> 이 값을 list =[]값에 넣어주는 작업을 하였습니다.

 

여기까지가 Create의 부분입니다. 데이터를 입력받고, 값을 저장하는데까지 하였습니다.

다음은 Read부분을 다음 코드로 이어서 진행하겠습니다.


1. Drawing()

->

function Drawing(){

 commentList.innerHTML = ""

   for(let i = list.length -1 ; i >= 0 ; i--){

     const row = createRow(list[i].userid , list[i].content,list[i].date);

     commentList.append(row);

    }

}

 

-> Create부분에서 데이터 입력은 끝났습니다. 이후에 Drawing()에서 반복문을 통하여

-> createRow(list[i].userid , list[i].content , list[i].date) 인자값을 넣어서 

-> HTML에 li를 생성하는 함수를 만들었습니다.

-> 함수에서 return된 값을 row라는 변수에 담아서

-> commentList.append를 통하여 자식의 값으로 대입하였습니다.

 


1.2 function createRow(){}

-> createRow함수는 주석에서 설명드리겠습니다

 

function createRow(userid,content,date){

  const ul = document.createElement("ul"); 

  const li1 = document.createElement("li");

  const li2 = document.createElement("li");

  const li3 = document.createElement("li");

// createElement를 통하여 ul , li를 생성하였고 그값을 각각의 변수에 넣었습니다.

 

 ul.append(li1);

 ul.append(li2);

 ul.append(li3);

// append메소드를 활용하여 ul의 자식으로 각각 li1 , li2 , li3을 넣었습니다

 

 ul.setAttribute("class" ,"comment-row");

 li1.setAttribute("class" , "comment-id");

 li2.setAttribute("class" , "comment-content");

 li3.setAttribute("class" , "comment-date");

 // setAttribute메소드를 활용하여 각각의 엘리먼트에 class를 부여하였습니다

 

 li1.innerHTML = userid;

 li2.innerHTML = content;

 li3.innerHTML = date;

 // 매개변수로 받은 값들을 각각 li1 , li2 , li3에 넣어주었습니다

 

 return ul; 

 // 완성된 ul을 return하였습니다.

}


-> 다시 함수를 호출하였던곳으로 돌아와 row 변수에 return되었던 ul값을 대입합니다.

 

function Drawing(){

 commentList.innerHTML = ""

   for(let i = list.length -1 ; i >= 0 ; i--){

     const row = createRow(list[i].userid , list[i].content,list[i].date);

     commentList.append(row);

    }

}

 

-> commentList에 append를 사용하여 반환된 ul값(입력한 데이터들)을 자식요소로 넣었습니다.

 


마지막으로 Drawing함수 호출한곳으로 돌아와서( function submitHandler() 맨아래쪽부분)

-> e.target.reset(); 즉 , form의 내용을 reset시켜달라는 메소드입니다.

 


 

이렇게 간단하게? 댓글을 입력하여(Create) 보여지는부분(Read) 까지 작성을 해보았습니다.

 

오늘 작업했던 것중 다시 보아야 할 부분들은

 

1. setAttribute("class","클래스명") -> 클래스를 추가해주는 메소드

 

2. append() -> 자식요소에 추가해주는 메소드

 

3. reset() -> reset시켜주는 메소드

 

4. createElement() -> Element를 생성해주는 메소드

 

5. e.preventDefault() -> 이벤트를 정지시켜주는 메소드

 

6. e.target.content -> e.target안에 있는 content의 값을 점표현식으로 가져오는것

 


 

하면할수록 너무어렵습니다.

부족한부분있으면 다음에 좀더 채워오도록 하겠습니다..

감사합니다