1.1 DOM구축 메소드 확인
1.2 데이터 확인
2.1 재귀로 데이터 불러오기
2.2 최종 완성, 코드 해석
이전 시간에 재귀에 대해 공부를 하였고 이 재귀를 어떻게 사용할 수 있을까 실습을 찾아보던중 좋은 예제를 찾아 실습 해보았다.
- 재귀로 DOM을 구축 및 설계
- 재귀를 활용해 구축한 DOM에 데이터를 추가하기
먼저 DOM을 구축하기 위해 HTML에 사용되는 용어들을 간략히 정리 해보았다.
const divele = document.createElement('div')
//div 엘리먼트를 생성
document.body.append('divele')
//body에 divele를 넣습니다.
divele.textContent = 'test'
//divele에 'test'라는 텍스트를 넣어줍니다.
이번에 사용할 예제 데이터는
const menu = [
{
type: '유럽',
name: '잉글랜드',
children: [
{
type: '프리미어리그',
name: '울버햄튼',
children: [
{ type: 'item', name: '황희찬' },
{ type: 'item', name: '후앙 네베스' },
{ type: 'item', name: '주앙 무티뉴' },
{ type: 'item', name: '조세 사' },
],
},
...<생략>
type: '유럽활동 목록',
name: '대한민국',
children: [
{ type: 'item', name: '손흥민(토트넘 핫스퍼)' },
{ type: 'item', name: '황희찬(울버햄튼)' },
{ type: 'item', name: '이강인(RCD마요르카)' },
{ type: 'item', name: '황의조(지롱댕 보르도)' },
],
},
];
배열안에 객체를 포함하고 객체안에 children이라는 Key에 더 세부적인 배열을 포함하는 방법입니다.
하드코딩으로 실습할 내용을 표현하면 아래 와같은 방식이다.
<ul>
<li> //children의 value값이 배열이 있는 경우
<input>
<span>나라이름 </span>
<ul>
<li> //children의 value값이 배열이 있는 경우
<input>
<span>팀이름</span>
<ul>
<li> //children의 value값이 undefined인경우
선수이름
</li>
...<생략>
</ul>
</li>
</ul>
</li>
</ul>
<출력되는 내용>
하지만 하드코딩으로는 데이터가 수정될경우 하나하나 바꿔야하는 번거로움이 있다.
우리는 데이터의 변경만으로도 내용이 바뀌는 방식을 구현할것이다.
<계획 수도코드>
1. DOM을 반복적으로 수행할 함수를 선언한다.
2. 내용을 붙일 ul element를 만들어 준다.
3. children이라는 key값을 확인하고 value값이 배열인지 아닌지 판별한다.
4. 배열일 경우 <li>,<input>,<span>을 만들어주고 value값을 올바르게 입력한다.
5. 마지막으로 다음 내용을 붙이기위해 <ul>을 만들어준다.
6. children의 value값이 undefined인경우
7. <li>태그를 만들어 name값을 출력합니다.
const getul = document.createElement('ul') //코드를 붙여줄 <ul>element 생성
document.body.append(getul) //body에 넣어준다.
function createTreeView(menu, currentNode) {
for (let i = 0; i < menu.length; i++) { //for문을 활용해서 배열을 하나씩 확인한다.
if(menu[i].children){ //입력받은 변수 menu의 i번쨰 index의 children의 값이 true일시
const createSpan = document.createElement('span');//<span>생성
const createLi = document.createElement('li');//<li>생성
const createUl = document.createElement('Ul')<ul>생성
const createInput = document.createElement('input');<input>생성
// li 안에 input과 span을 append
createLi.append(createInput);
createLi.append(createSpan);
// input에 checkbox type 생성
createInput.setAttribute('type', 'checkbox');
// 카테고리 - name = menu[i].name => span 태그 안에 textcontent
createSpan.textContent = menu[i].name;
// currentNode에 li append하기
currentNode.append(createLi)
// 다음내용을 붙여주기 위해 ul을 생성한다.
createLi.append(createUl)
//함수를 다시 재귀하여 배열의 객체들의 내용을 확인한다.
//(해당 i번째 index의childen을 확인하는 value로,
//다음내용을 붙여주기위해 생성한 <ul>을 내용을 붙여줄 element변수로 넣어준다.
createTreeView(menu[i].children,createUl)
}
else{ // children이 없는경우 (재귀탈출문)
const createLi = document.createElement('li');//<li>생성
createLi.textContent = menu[i].name;//li의 text를 name로 정한다.
currentNode.append(createLi) //li를 입력받은 변수 currentNode에 넣어준다.
}
}
}
createTreeView(menu, getul);