ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JS -P(5) 게시판 조회수/삭제버튼 구현하기
    JS practice 2022. 11. 19. 15:08
    728x90

    전 부분에서 게시판을 만들어보신 분들은 이제 여러가지를 만들어 보고 싶을 것이다. 뭐 삭제버튼을 만들어 보고 싶을 수도

     

    있고 아니면 조회수를 구현해보고 싶을 수도 있을 것이다.

     

    오늘은 본인이 구현한 두가지를 여러분들께 보여드리려고 한다. 

     

    주의할 점은 더 좋은 메서드들이 있을 수 있고, 더 간편한 방법이 있을 수 있다.

     

    그런 경우 공유해주시면 감사드리겠다. (본인은 아직 하드코딩 레벨)

     

    우선 본인은 리스트에서 최대한 많은 부분을 처리하려고 했다. 물론 수정탭에서 삭제버튼을 구현하거나, 할수도 있지만

     

    리스트에서 삭제버튼을 만들고, 리스트의 어떤 부분을 이용해서 조회수를 구현했다는것을 먼저 말씀드린다. 

     

    1. 구현부분을 먼저 살펴보도록 하자. 

     

    우선 앞의 template 부분에서 추가해줄 부분이 두 군데 존재한다.  

     

    function template(item,index){
        return `
        <tr>
            <td>${item.index}</td>
            <td><a href="/board/view.html?index=${index}" data-index="${index}" id="asmr">${item.subject}</td>
            <td>${item.content}</td>
            <td>${item.date}</td>
            <td>${item.hit}</td>
            <td id="del" data-index="${index}" style ="cursor:pointer;">${item.delete}</td>
        `
    }

    1) a(앵커)태그에 data-index를 부여하고

    2) id를 부여한다. 

     

    이는 밑에서 이벤트를 부여하기 위해서 설정해놓았다고 생각하면 된다.

     

    const asmr = document.querySelectorAll("#asmr")
    
    
    function shi(e){
        if(e.type==="click"){
            // e.preventDefault()
            const item =localStorage.getItem("boards")
            const board = JSON.parse(item)
            const sit = e.target.dataset.index
            for(let i=0; i<board.length;i++){
                if(+sit === i){
                    board[i].hit +=1
                    const add= JSON.stringify(board)
                    localStorage.setItem("boards", add)
                }
            }
            
        }
    }
    
    for(let i=0; i <boards.length;i++){
    asmr[i].addEventListener("click", shi)
    }

    먼저 asmr 태그를 js에서 호출해주고 

     

    asmr태그는 각자 생성되기 때문에 for문을 통해서 각각 하나의 앵커태그마다 이벤트를 부여해준다. 

     

    다음으로 부여한 이벤트는 click 이벤트가 발생했을때만 발생하도록 if문을 걸어주고 (생각해보면 걸어줄 필요는 없었던것 같다. 리팩토링 하도록 하겠다)

     

    다음으로는 localstorage에서 데이터를 불러오고 우리가 사용할 수 있도록 데이터를 손질해주자.

     

    다음으로 우리가 사용할 dataset.index를 불러와주고 그것을 sit에 저장한다. 

     

    마찬가지로 board도 여러개의 배열이기 때문에 for문을 사용해서 조건을 걸어주자. 

     

    이때 주의할점은 sit가 데이터 타입을 확인했을때 문자 타입이기때문에 숫자 타입으로 바꿔서 조건을 비교해주면 

     

    우리가 한번 클릭했을때 조회수가 추가되는 것을 볼 수 있다. 

     

    2. Delete도 이와 같은 메커니즘이다.

     

    function template(item,index){
        return `
        <tr>
            <td>${item.index}</td>
            <td><a href="/board/view.html?index=${index}" data-index="${index}" id="asmr">${item.subject}</td>
            <td>${item.content}</td>
            <td>${item.date}</td>
            <td>${item.hit}</td>
            <td id="del" data-index="${index}" style ="cursor:pointer;">${item.delete}</td>
        `
    }

     

    마지막 del 부분을 보면 마찬가지로 data-index와 style이 적용된 것을 볼 수 있다.

     

    style은 cursor 효과를 주기위해 작성하였고 data-index는 또한 우리가 구분지어서 사용하기 위해 작성하였다. 

     

    const del = document.querySelectorAll("#del")
    
    for(let i=0; i<del.length;i++){
        function init(e){
            if(confirm("정말 지우시겠습니까?")){
            const item =localStorage.getItem("boards")
            const num = e.target.dataset.index
            const board = JSON.parse(item)
            board.splice(num,1)
            const nem = JSON.stringify(board)
            localStorage.setItem("boards", nem)
            window.location.href = `/board/list.html`}
            else return
        }
    
        del[i].addEventListener("click", init)
    }
    
    const asmr = document.querySelectorAll("#asmr")

    위의 설명과 같이 한번 이해해보시면 좋을것 같다. 

    'JS practice' 카테고리의 다른 글

    JS-P (4)  (0) 2022.11.18
    JS -P(3) : 게시판  (1) 2022.11.17
    JS-P (2)  (0) 2022.11.15
    JS -P (1)  (0) 2022.11.14

    댓글

Designed by Tistory.