본문 바로가기
js

tree_ui

by Nick Black 2020. 11. 19.
반응형
function createTreeView(menu, root) {
  menu.forEach(function(el){
    if (el.children === undefined){
      const li = document.createElement('li')
      root.append(li)
      li.textContent = el.name
    }
    if (el.children !== undefined){
      const li = document.createElement('li')
      const input = document.createElement('input')
      const span = document.createElement('span')
      const ul = document.createElement('ul')
      root.append(li)
      li.append(input,span,ul)
      input.type = 'checkbox'
      span.textContent = el.name
      createTreeView(el.children,ul)
    }  
  })
}

매개변수 menu는 객체 root는 document.querySelector('#root')로 받아서
menu[0].children이 있다면 createTreeView 라는 함수를 호출해서
children이 없을때 까지 반복을 하는 재귀 함수 입니다

하나 하나 살펴 볼까요?

function createTreeView(menu, root) {
  menu.forEach(function(el){
	//11.계속해서 재귀를 하다가 결국에 children이 없다면 중단하는 부분입니다
    if (el.children === undefined){
	//12.변수 li은 엘리먼트 li를 추가하는 변수
      const li = document.createElement('li')
    //13.위치값 root에 변수 li을 append 합니다
      root.append(li)
    //14. 위치값 li에 textContent를 추가 시켜주는데 el.name 을 추가 시켜 줍니다
      li.textContent = el.name
	// 여기서 종료를 해야하므로 재귀는 없습니다
    }
	//1. el.children이 존재 한다면
    if (el.children !== undefined){
	//2. 변수 li은 엘리먼트 li를 추가하는 변수
      const li = document.createElement('li')
	//3. 변수 input은 엘리먼트 input을 추가하는 변수
      const input = document.createElement('input')
	//4. 변수 span은 엘리먼트 span을 추가하는 변수
      const span = document.createElement('span')
	//5.변수 ul은 엘리먼트 ul을 추가하는 변수
      const ul = document.createElement('ul')
      //6. 매개변수 root를 이용해서 변수 li을 append 해줍니다
      root.append(li)
      //7. li은 위치값(?)이 되고 li에 변수 input,span,ul 을 append 해줍니다
      li.append(input,span,ul)
      //8. input에 type을 'checkbox'로 설정을 해줍니다
      input.type = 'checkbox'
      //9. span에 textContent를 추가를 시켜주는데 el.name의 값을 추가를 시켜줍니다
      span.textContent = el.name
      //10.children 이 존재 하기에 한번 더 이 과정을 해줘야하기 때문에 재귀를 사용합니다
	  //매개변수 menu를 el.children으로 교체 해주고 root를 ul로 교체를 해줍니다
      createTreeView(el.children,ul)
    }  
  })
}
const root = document.getElementById('root');

수도 코드 순서대로 읽으시는게 더 편하실테니 한눈에 보기 쉽게 작성 하였습니다
여기서 제일 중요한게 10번 수도코드 아래 있는 재귀 함수 입니다
매개변수를 변경시켜주어야 하니 계속 변해야 한다는 점 유의 하시면 어떤 문제가 나와도 괜찮겠습니다

긴글 읽으시느라 수고 많으셨습니다
여기까지 간단한 tree ui 재귀에 대해서 알아보았습니다 감사합니다

반응형