JavaScript로 캘린더 월 변경 화살표 구현
이제 캘린더 아래에 월 변경을 위한 화살표를 만들어 봅시다. HTML 코드를 수정해 보겠습니다:
<div id="parent">
<div id="calendar">
<div class="info">1월 2020</div>
<table>
<thead>
<tr>
<th>월</th>
<th>화</th>
<th>수</th>
<th>목</th>
<th>금</th>
<th>토</th>
<th>일</th>
</tr>
</thead>
<tbody class="body"></tbody>
</table>
<div class="nav">
<a href="#" class="prev">←</a>
<a href="#" class="next">→</a>
</div>
</div>
</div>
CSS 코드도 수정해 보겠습니다:
#parent {
text-align: center;
}
#calendar {
display: inline-block;
}
#calendar td, #calendar th {
padding: 10px;
border: 1px solid black;
text-align: center;
}
#calendar .nav, #calendar .info {
text-align: center;
}
#calendar a {
color: blue;
font-size: 25px;
text-decoration: none;
}
#calendar a:hover {
color: red;
}
#calendar .active {
color: red;
}
화살표 링크를 변수에 할당하겠습니다:
let prev = calendar.querySelector('.prev');
let next = calendar.querySelector('.next');
토론
이제 문제를 어떻게 해결할지 논의해 봅시다.
사실 우리의 캘린더 코드는 확장성이 좋게 작성되어 있습니다:
주어진 월의 캘린더를 그리는 draw 함수가 있습니다.
따라서 화살표를 클릭할 때 다른 월(및 연도) 번호로
캘린더를 다시 그릴 수 있습니다.
다음 월 화살표 클릭 시 우리가 할 수 있는 작업의 예시입니다:
next.addEventListener('click', function() {
draw(body, getNextYear(year, month), getNextMonth(month));
});
여기서는 getNextYear와 getNextMonth 함수가
사용됩니다. 이 함수들이 무엇을 해야 하는지 논의해 보겠습니다.
함수 이름에서 알 수 있듯이, getNextYear 함수는
다음 연도를 가져옵니다. 여기서 의미하는 바는,
현재가 12월인 경우 다음 월로 전환할 때
연도가 1 증가해야 한다는 것입니다.
현재가 12월이 아닌 경우, 함수는 단순히 현재 연도를
반환해야 합니다.
getNextMonth 함수는 다음 월을 가져와야 합니다.
이 함수는 12월을 제외한 모든 월에 대해 월 번호에
1을 더할 것입니다. 12월의 경우 다음 월은
번호 0인 1월이 될 것입니다.
이전 월 버튼을 클릭할 때도 유사한 작업을 수행해야 합니다:
prev.addEventListener('click', function() {
draw(body, getPrevYear(year, month), getPrevMonth(month));
});
월 변경 버튼의 기능을 구현하세요.
캘린더 상단의 정보가 표시되는 월 및 연도와 일치하도록 만드세요.