시계를 만들 div를 그안에 h1을 html에 새로이 작성한다.
<div class = js-clock>
<h1>00:00</h1>
</div>
const clockContainer = document.querySelector(".js-clock");
const clockTitle = clockContainer.querySelector("h1");
//여기서 변수설정을 통해 selector를 이용하여 필요 부분들을 불러와줌.
function getTime(){
const date = new Date();
const minutes = date.getMinutes();
const hours = date.getHours();
const seconds = date.getSeconds();
clockTitle.innerText = `${hours}:${minutes}:${seconds}`;
}
//date 객체 사용하여 각 변수를 지정한 함수로 만들어줌. innerText는 해당 내부값 변경해주는 것임.
function init() {
getTime();
}
//실행을 위한 init()함수는 초기에 세팅
init();
이렇게하면 시계가 생긴다.
const clockContainer = document.querySelector(".js-clock");
const clockTitle = clockContainer.querySelector("h1");
function getTime(){
const date = new Date();
const minutes = date.getMinutes();
const hours = date.getHours();
const seconds = date.getSeconds();
clockTitle.innerText = `${hours < 10 ?`0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
//삼항연산자라고 함 if -> ? else - > : 가 됨 mini if이다.
}
function init() {
getTime();
setInterval(getTime, 1000);
}
init();
hours < 10 ? `0${hours}` : hours
이렇게 하면 개발자도구에서 매초 h1 태그 내의 시간이 변경되는 것을 볼 수 있음(화면이 당연히 나옴)
끝