[JS & Jquery] 표 자동추가 라이브러리 제작

JIOO·2023년 6월 27일
0

ES6

목록 보기
12/17
post-thumbnail

문제확인

홈페이지에 게시 되어 있는 표(table)인데 관리자페이지에 이 표를 제어 할 수 있는 컨트롤러가 없어서 수동으로 html을 추가해줘야 하는 상황. 비효율적이라고 요청이 옴.

(이전 작업했을 시 주기적으로 추가되야하는지 몰랐다함)

문제분석

  1. 1개의 파일에 10개의 논문명,학술지명,개체연월,비고를 넣었을 때 자동으로 html이 랜더링 되어야함.
  2. 줄의 갯수에 따라 넘버가 자동으로 붙어야함.

📝 수동으로 일일이 하드코딩 할 순 없으니 방법을 찾던중 array에 object를 담아 쓰면 될듯

이름과 값을 넣어야하면 Object를 써야함.
예) id : 1, title : "title"

const txtData = [
    {
        title: "Development of a Human Pose Recognition System based on MediaPipe Pose, an Optimization Method, and a Humanoid Robot Model",
        name: "ISIS2021 (The 22th International Symposium on Advanced Intelligent Systems)",
        date: "2021.10",
        other: ""
        },
    {
        title: "Predicting the modal frequencies of a cracked beam considering crack modes Ⅰ and Ⅱ",
        name: "EASEC17 (The 17th East Asia-Pacific Conference on Structural Engineering & Construction)",
        date: "2022.06",
        other: ""
        },
    {
        title: "Crack assessment of beam using machine learning with augmented sensing",
        name: "EASEC17 (The 17th East Asia-Pacific Conference on Structural Engineering & Construction)",
        date: "2022.06",
        other: ""
        },
]

이런식으로 array 안에 object를 넣고 이걸 api인 샘 치고 불러올거임.


📝 이제 api도 생겼으니 불러와서 자동으로 html이 생성되게 하면됨

완성되어야 하는 html 구조


💻 코드 (해결법을 찾다 Jquery를 불가피하게 사용하게 됨)

<스크립트 src="data.js"></script>
//이렇게 위에 선언해주면 data.js에 있는 txtData가 해당 페이지의 console에 잡힘

$(document).ready(function() {
//jquery 사용을 위해 ready
  const target = document.getElementsByClassName("cell-area")[0]
  const api = txtData[0]
  // txtData를 api로 선언 해준 후 
  
  const count = Object.keys(api).length + 1;
  api의 키의 갯수, 즉) 논문명,학술지명,개체연월,비고 를 뜻함
  // +1을 해준 이유는 맨 첫칸 넘버링이 들어가야 하기 때문
  
  const p = document.createElement("p")
  const div = document.createElement("div")
  //자동으로 쓸 div과 p를 미리 만들어 둠.

  for(let i = 0; i < api.length; i++) {
  //api.length가 안되면 txtData.length를 사용하여 for문을 돌림 
  
    const row = $(div).clone().addClass(`table-row table-${i}`)
  // api의 갯수만큼 row 가로 줄을 만든 후 

    for(let j = 0; j < count; j++) {
 	   // 1줄의 가로줄 안에 5개의 세로칸이 들어가야 되는 상황이라 count로 2중 for문
       
        const cell = $(div).clone().addClass("table-cell");
        const peace = $(p).clone().addClass("table_txt");
 		//자동으로 쓸 div과 p를 미리 만들어 둠 (클래스도 미리 넣어줌)
        
        if(j === 0) {
            $(p).clone().addClass("table_txt table_vue").appendTo(cell)
            // p를 생성해서 말머리 클래스 (table_vue 추가)를 넣어주고 cell을 넣어줌 
        } else if (j === 1) {
            peace.text(txtData[i].title).appendTo(cell)
            // 논문명
        } else if (j === 2) {
            peace.text(txtData[i].name).appendTo(cell)
            //학술지명
        } else if (j === 3) {
            peace.text(txtData[i].date).appendTo(cell)
            //개체연월
        } else if (j === 4) {
            peace.text(txtData[i].other).appendTo(cell)
            //비고
        } else { 
            peace.appendTo(cell)
            //혹시 모를 나머지
        }

        $(cell).clone().appendTo(row)
        //위 cell을 만든 후 row에 넣어줌
    }

    $(row).clone().appendTo(target)
    //마지막으로 row를 cell_area에 넣어줌
  } 
})

📝 이제 맨 앞 넘버링을 만들어주면 됨

function autoIncrement(startnum,index) {
            var init = startnum;
            var td_list = document.getElementsByClassName("table_vue");
            //페이지에 랜더링 된 모든 table_vue(말머리 클래스)를 찾아줌
            for (var i = 0; i < td_list.length; i++) {
                init++;
                //1씩 증가해서 
                if(init > 10 && index === 0) {
                  td_list[i].innerHTML = "&nbsp" + init;
                 //innerHtml로 1~9넣어줌 ![](https://velog.velcdn.com/images/jioo/post/0b87fc85-1a80-41f8-910f-7f6955808ec8/image.JPG)

                } else if (init > 10 ) {
                  td_list[i].innerHTML = "&nbsp" + index + init;
                  // index = 만약 index가 3일때 31~39
                } else if ( init === 10 ) {
                  init = `${init} + (${index} * 10)`
                  td_list[i].innerHTML = "&nbsp" + init;
                  //init이 10일 때 10 + (index번호 * 10) = 31에서 시작해서 40으로 끝남
             }
      }
 }


window.onload("load",function(){
 autoIncrement(0,index) // 홈페이지가 랜더링 되면서 
 autoIncrement 함수를 실행하면서 parameter값을 0과 페이지 인덱스를 넣어줌
})

🧑🏻‍💻 Pure Js 변환

const target = document.getElementsByClassName("cell-area")[0]
const count = Object.keys(txtData[0]).length + 1;
const p = document.createElement("p");
const div = document.createElement("div");

for(let i = 0; i < txtData.length; i++) {
  const row = div.cloneNode(true);
  row.classList.add(`table-row`, `table-${i}`);
  
  for(let j = 0; j < count; j++) {
      const cell = div.cloneNode(true);
      cell.classList.add("table-cell");
      const peace = p.cloneNode(true);
      peace.classList.add("table_txt");

      if(j === 0) {
          const pClone = p.cloneNode(true);
          pClone.classList.add("table_txt", "table_vue");
          cell.appendChild(pClone);
      } else if (j === 1) {
          peace.textContent = txtData[i].title;
          cell.appendChild(peace);
      } else if (j === 2) {
          peace.textContent = txtData[i].name;
          cell.appendChild(peace);
      } else if (j === 3) {
          peace.textContent = txtData[i].date;
          cell.appendChild(peace);
      } else if (j === 4) {
          peace.textContent = txtData[i].other;
          cell.appendChild(peace);
      } else { 
          cell.appendChild(peace);
      }

      row.appendChild(cell.cloneNode(true));
  }

  target.appendChild(row.cloneNode(true));
}

💻 라이브러리가 적용된 파일구조


💻 라이브러리가 적용된 페이지
https://i-soc.re.kr/sub/sci/performance/performance.html

profile
프론트엔드가 좋은 웹쟁이 with Notion (요즘은 노션과 병행 중)

0개의 댓글