1)함수1-1)date + setInterval1-2) 시간관련함수2) 이벤트
2-1) 기본이벤트
2-2)인라인
2-3)표준
2-4) 정리
2-5) 예제
3) 다양한 이벤트
3-1)key Event
3-2) 태그의 기본이벤트
3-3)submit event
4)배열
4-1)배열의선언
4-2 )배열에 값저장
4-3)배열관련메서드 (indexOf)
5) 예제
2025.03.20 - [JavaScript] - 부트캠프34일차(JS[요소조회출력, 문자열,Math, 조건문])
부트캠프34일차(JS[요소조회출력, 문자열,Math, 조건문])
1) 요소출력1-1) id속성값 이용1-2)태그이름 이용1-3)name속성 이용1-4)class속성값 이용1-5)선택자를 이용1-6) 정리2)문자열2-1)기본메서드2-2)문자열관련 HTML(비권장) 3)Math3-1)숫자관련메서드3-2)문자열 숫
ddkk1120.tistory.com
어제 한 Date에 이어지는 내용!
1) 함수
1-1) date + setInterval
해당 함수들은 시계를 만들기 위한 함수들
<style>
.over50second{color: red;}
</style>
<body>
<div id="box1" class="area"></div>
<h1 id="counter">
<span id="year"></span>년
<span id="month"></span>월
<span id="date"></span>일
<span id="hour"></span>시
<span id="minute"></span>분
<span id="second"></span>초
<span id="mil"></span>
</h1>
<script src="ex09_Date.js"></script>
</body>
setInterval(함수,밀리초) : 밀리초마다 함수를 실행
className = 'class속성의 이름 ' : class속성명 설정
document.querySelector("#counter").className = 'over50second';
<hi id = "counter" class="over50second"> </hi>로 설정한단 뜻
className=' ' :등록된 class속성의값을 제거
document.querySelector("#counter").className = '';
setAttribute : 속성 등록 함수
setAttribute(속성명,속성값): <h1 id="counter" class = "over50second"></h1>e
ex)document.querySelector("#counter").setAttribute("class",'over50second');
removeAttribute(속성명) : 속성명 제거
function fnFillZero(n){
return n <10 ? '0'+n : n;
//10보다 작을 떄 앞에 0 문자열을 덧붙여줌(자릿수보정)
}
//우리가만든 함수가 아닌 자바스크립트의함수
//setInterval(함수,밀리초) : 밀리초마다 함수를 실행
setInterval(function(){
let now = new Date();
document.querySelector("#year").textContent = now.getFullYear();//2025
document.querySelector("#month").textContent = fnFillZero(now.getMonth()+1);//03
document.querySelector("#date").textContent = fnFillZero(now.getDate());//21
document.querySelector("#hour").textContent = fnFillZero(now.getHours());
document.querySelector("#minute").textContent = fnFillZero(now.getMinutes());
document.querySelector("#second").textContent = fnFillZero(now.getSeconds());
document.querySelector("#mil").textContent = fnFillZero(now.getMilliseconds());
if(now.getSeconds() >=50){
//className : class속성의 이름
// <hi id = "counter" class="over50second"> </hi>로 설정한단 뜻
document.querySelector("#counter").className = 'over50second';
//setAttribute : 속성 등록 함수
//setAttribute(속성명,속성값): <h1 id="counter" class = "over50second"></h1>
// document.querySelector("#counter").setAttribute("class",'over50second');
}else{
//className='' :등록된 class속성의값을 제거
document.querySelector("#counter").className = '';
// document.querySelector("#counter").removeAttribute("class");
//removeAttribute(속성명) : 속성명 제거
}
},100);//0.1초마다 함수를 실행하는것임
1- 2) 시간과 관련된 함수
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3>setTimeOut</h3>
<ul>
<li>let id = setTimeout(함수,밀리초)</li>
</ul>
<hr>
<h3>setInterval</h3>
<ul>
<li>let id = setInterval(함수,밀리초)</li>
<li>밀리초마다 반복해서 함수 실행</li>
<li>clearInterval(id) : setInterval로 설정된 함수 중지</li>
</ul>
<script src="ex10_timer.js"></script>
</body>
</html>
setTimeout(함수,밀리초) : 밀리초 후에 함수 실행
setInterval(함수,밀리초) : 밀리초마다 함수 실행(무한)
clearInterval(id) : setInterval로 설정된 함수 중지
// let timerid = setTimeout(function(){
// console.log("3초 후 출력")
// },3000) //3초 후 딱 한번만 실행
let n = 0;
let timerid2 = setInterval(function(){
console.log(n++);
},1000)
setTimeout(function(){
clearInterval(timerid2);
console.log(timerid2+"중지됨")
},5000)
2) 이벤트
2-1) 기본이벤트방식
<body>
<h1>이벤트(Event)</h1>
<h3>기본이벤트</h3>
<p>
특정 요소 객체의 이벤트 속성 접근 후 이벤트핸들러연결방식
</p>
<button id="btn1">실행확인1</button>
<button id="btn2">실행확인2</button>
<div id="area1" class="area"></div>
<script>
const area1 = document.querySelector("#area1");
//이벤트 핸들러 : 이벤트 발생 시 호출되는 함수
document.querySelector("#btn1").onclick = function(){
area1.innerHTML += "btn1 버튼이클릭 되었어요 <br>";
}
document.querySelector("#btn2").onclick = function(){
area1.innerHTML += "btn2 버튼이클릭 되었어요 btn1이벤트 제거 <br>";
document.querySelector("#btn1").onclick = null;
//이벤트핸들러제거
}
</script>
2-2) 인라인 방식
<!----------------------------------------------------------->
<h3>인라인 방식 이벤트</h3>
<p>
요소 내부에 직접 이벤트 속성을 제시해 핸들러 정의
</p>
<button onclick="document.querySelector('#area2').innerHTML+=`첫번쨰버튼클릭<br>`">
실행확인1</button><!-- 함수로 빼서하는 걸 추천-->
<button onclick="test1();">실행확인2</button> <!--함수 이용-->
<div id="area2" class="area"></div>
<script>
function test1(){
document.querySelector("#area2").innerHTML +=`두번쨰 버튼 클릭<br>`
}
</script>
</body>
2-3)표준
addEventListener (이벤트,함수) : 이벤트 발생 시 함수실행(핸들러호출)
이벤트종류
click : 클릭 시
mouseenter : 마우스를 가져다 댔을 때
mouserout : 마우스가 버튼에서 벗어나 있을 떄
<h3>표준 이벤트 모델(addEventListener)</h3>
<p>w3c에서 공식적으로 지정한 이벤트모델</p>
<button id="btn3">실행확인</button>
<script>
const btn3 = document.querySelector("#btn3");
btn3.addEventListener("click",function(){
alert("표준이벤트 모델 테스트")
})
btn3.addEventListener("mouseenter",function(){
//mouserenter를 리스너에등록후 이벤트발생 시 함수실행(핸들러호출)
//"mouseenter : 마우스를 가져다 댔을 떄
btn3.style.backgroundColor="red";
})
btn3.addEventListener("mouseout",function(){
//"mouseenter : 마우스가 버튼을 벗어날 때
btn3.style.backgroundColor=null;
})
</script>
2-4) 정리
고전이벤트방식
<button id="btn4">고전이벤트방식</button>
<script>
document.querySelector("#btn4").onclick = function(e){
//e : 이벤트객체 . 이벤트정보를 저장하고있는객체
console.log("e : ",e);
console.log("e.target : ",e.target); // 이벤트 발생된 요소
console.log("window.event : ",window.event);//이벤트 객체
console.log("window.event.target : ",window.event.target);
console.log("this : ",this);//이벤트발생된 요소 객체
e.target.innerHTML = '버튼 클릭됨'
window.event.target.style.backgroundColor = "red";
this.style.color = 'white';
}
</script>
표준이벤트방식
<button id="btn5">표준이벤트방식</button>
<script>
document.querySelector("#btn5").addEventListener("click",function(e){
console.log("e.targer:",e.target);
console.log("window.event.targer:",window.event.target);
console.log("this : ",this); // 이벤트가 발생된 요소객체들
this.style.color = "red";
})
</script>
인라인 이벤트방식1
window.event.target : 이벤트가발생한 객체
<button onclick="test2();">인라인 이벤트방식1</button>
<script>
function test2(){//이벤트 핸들러 기능,함수
console.log("window.event.target : ",window.event.target);
window.event.target.innerHTML = '버튼변경';
console.log("this : ",this);
//여기서의this는 이벤트발생된 객체X , window객체임
}
</script>
인라인 이벤트방식2
<button onclick="test3(this);">인라인 이벤트방식2</button>
<!-- 인라인방식에서의 this : 현재 객체(target)-->
<script>
function test3(btn){
btn.innerHTML = "버튼내용변경2";
btn.style.backgroundColor = "red";
console.log("btn : ",btn);
}
</script>
2-5) 예제)
<br><hr>
<h4>클릭시 button 태그의 내용으로 색이 바뀌도록</h4>
<button onclick="changeBackground();">red</button>
<button onclick="changeBackground();">blue</button>
<button onclick="changeBackground();">green</button>
<button onclick="changeBackground();">pink</button>
<script>
function changeBackground(){
//이벤트가 발생한객체의 backgroundColor <-- 이벤트발생한 태그의 요소이름
window.event.target.style.backgroundColor = window.event.target.innerHTML;
}
</script>
예제2)
window.event.target : 이벤트가발생한 태그
if문 or switch문 모두 사용해도무관!!!
<hr><br>
<h4>button 태그를 클릭 시 배경색변경!!{버튼1 : 빨강 버튼2: 파랑 , 버튼3 : 초록} </h4>
<button onclick="changeBackground2();">버튼1</button>
<button onclick="changeBackground2();">버튼2</button>
<button onclick="changeBackground2();">버튼3</button>
<script>
function changeBackground2(){
const btn = window.event.target
if(btn.innerHTML == '버튼1'){
btn.style.backgroundColor = 'red';
}
else if(btn.innerHTML == '버튼2'){
btn.style.backgroundColor = 'blue';
}
else if(btn.innerHTML == '버튼3'){
btn.style.backgroundColor = 'green';
}
// switch(btn.innerHTML){
// case '버튼1' : btn.style.backgroundColor = 'red'; break;
// case '버튼2' : btn.style.backgroundColor = 'blue'; break;
// case '버튼3' : btn.style.backgroundColor = 'green'; break;
// }
}
</script>
예제3)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>select</p>
<form name="f">
<table>
<tr><td><select name="s" onchange="drawimg()">
<option value="strawberry.gif">딸기</option>
<option value="banana.jpg">바나나</option>
<option value="apple.gif">사과</option>
</select></td>
<td><img name="img2" src="img/strawberry.gif" width="100" height="120">
</td></tr></table>
</form>
<script src="ex11_exam.js"></script>
</body>
</html>
function drawimg(){
// let img2 = document.querySelector("img[name=img2]");
// console.log(img2)
// img2.src = "img/"+document.querySelector("select[name=s]").value;
// let img2 = document.getElementsByName("img2")[0];
// img2.src ="img/"+document.getElementsByName("s")[0].value;
let img2 = document.img2; //BOM : Browser Object Model
img2.src = "img/"+document.f.s.value;
}
3) 다양한이벤트
3-1) key Event
keydown : 키보드에서 키가 눌려질 떄 발생<br>
keypress : 키보드에서 키가 눌려져있는 상태 .
F키(F1~F12),기능키 등에서는 발생X <br>
keyup => 키가 올라올떄(키에서 손을 뗄 때)
<body>
<h2>key이벤트</h2>
<p>
- keydown | keypress => 키가 눌려질 떄 발생되는 이벤트<br>
> keydown : 키보드에서 키가 눌려질 떄 발생<br>
> keypress : 키보드에서 키가 눌려져있는 상태 .
F키(F1~F12),기능키 등에서는 발생X <br>
- keyup => 키가 올라올떄(키에서 손을 뗄 때)
</p>
<input type="text" id="userName">
</body>
document.getElementById("userName").onkeyup = function(e){
console.log("e:",e); //key이벤트객체
console.log("this.value : ",this.value);//input태그의 value
console.log("e.key : "+e.key);//눌려진키의 key값
console.log("e.keyCode : "+e.keyCode);//눌려진 키의 code값
}
3-2) 태그별로 기본적으로 가지고있는 이벤트
return false; 로 태그의 기본이벤트를 막을 수 있다
<body>
<br><hr>
<h2>태그별로 기본적으로 가지고 있는 이벤트제거</h2>
<p>
-a태그 :클릭시 href속성에쓰여져있는 url을 요청하는 기본이벤트
-form 태그의 submit버튼 : submit버튼 클릭시 form태그의action속성에
쓰여져있는 url로 입력값들과 함꼐 요청하는 기본이벤트존재
--태그 내에 기본설정된 이벤트의 실행을 막을때는 return false로설정<br>
</p>
<!--연결못하게하는 방법중에 주소앞에 # 을 붙이는 방법도있음-->
<!-- onclick에 return false를 넣어주면 아무일도 일어나지않음-->
<a href="http://www.naver.com" onclick="alert('네이버연결 못함');return false">네이버 이동</a><br>
<a href="http://www.google.com" onclick="return test4();">구글로 이동</a><br>
</body>
<script src="ex12_이벤트2.js"></script>
JS
function test4(){
return confirm("구글페이지로 이동하시겠어요?" );
// if(confirm("구글페이지로 이동하시겠어요?" )){
// return true; //확인버튼 누를 시 true 반환
// }
// else{
// return false; //취소버튼 누르면 false반환
// }
}
3-3) submit Event
<body>
<form action="ex11_exam(event).html" method="post">
<!--method방식이 get이면
submit 시 action의 링크로 이동하게됨 post로 바꾸자
name의 정보가 같이넘어가게됨(정보유출위험)-->
아이디: <input type="text" id="userId" name="userId" required><br>
비밀번호 : <input type="password" id="userpw" name="userpw" required><br>
<input type="submit"value="전송" onclick="return validate();">
</form>
<script src="ex12_이벤트2.js"></script>
</body>
if문과 charAt를이용(아스키코드로 문자 판별)
function validate(){
//아이디유효성검사 : 영문자 or 숫자로만 5글자이상 12글자 이하 가능
// 형식에 맞지않는 경우 => 알림창 출력 . 기본이벤트 막기
//형식에맞다면 그냥 submit
const userId = document.getElementById("userId").value;
if(userId.length>=5 && userId.length<=12){
for(let i=0 ; i<userId.length;i++){
if(userId.charAt(i)>=0 && userId.charAt(i)<=9
||userId.charAt(i)>='A' && userId.charAt(i)<='z'){
}
else{
alert("숫자 or 영문자만 입력하시오")
return false;
}
}return true;
}
else{
alert("5자리~12자리 사이만 입력")
return false;
// }
}
정규식을 이용한 방법
function validate(){
const userId = document.getElementById("userId").value;
//정규식을 이용해 아이디 유효성 검사하기
const regExp = /^[a-z0-9]{5,12}$/i;
//소문자의 아스키코드 > 대문자아스키코드
if(!regExp.test(userId)){//정규표현식과 일치하지않는다면
alert("유효한 아이디의형식X 다시입력")
document.getElementById("userId").select();
//잘못입력된 텍스트를 선택해줌
return false;
}
}
4) 배열
4-1) 배열의선언과 초기화
<body>
<h1>배열</h1>
<p>자바스크립트에서는 변수선언시 별도의 자료형 지정x 어떤자료형이든
하나의 배열에 저장 <br>
크기에 제한X , 자바의 ArrayList와 비슷함<br>
[] 표기법 사용 <br>
</p>
<button onclick="arrayTest1();">확인</button>
<script src="ex13_배열.js"></script>
</body>
JS
function arrayTest1(){
const arr = ["홍길동",20,"서울",true ,[1,2,3]]; //배열의선언, 초기화
console.log(arr);
console.log(arr[2]);
console.log(arr[4]);
console.log(arr[4][1]);
}
4-2) 배열에 값 저장 및 조회
<button onclick="arrayTest2()">확인2</button>
function arrayTest2(){
const arr1 = new Array();//크기0의배열
const arr2 = new Array(3);
const arr3 = [];//크기0의배열
console.log(arr1.length , arr2.length , arr3.length);
console.log(arr2);
//자바스크립트는 크기가 0이어도 배열에값넣기가 가능
arr3[0] = "바나나";
arr3[1] = "사과";
arr3[9] = true;
console.log(arr3 , arr3.length)
//arr3배열출력하기 : 기존for구문이용
//1 모든배열의요소가 출력 값이없는경우 undefined
//2.일부만 조회 가능(범위설정)
for(i=0 ; i<arr3.length ; i++){
console.log("arr3 : ",i,":",arr3[i]);
}
//for in 구문
// 1.undefined 값은 출력X
//2. 모든요소를 조회함
for(let i in arr3){
console.log(`arr3[${i}]=${arr3[i]}`)
}
}
4-3) 배열관련메서드
<h3>배열관련 메서드</h3>
<h4>배열.indexOf(요소) : 배열에서 요소의 위치값 리턴</h4>
<button onclick="indexofTest();">확인3</button>
<div class="area" id="area1"> </div>
<script src="ex13_배열.js"></script>
function indexofTest(){
const area1 = document.querySelector("#area1");
const arr = ["사과","딸기 ", "레드향" , "바나나","키위","한라봉"]
const search = prompt("위치를 찾고싶은 과일명을 입력");
let index = arr.indexOf(search);
area1.innerHTML += `당신이 찾는과일 : ${search}은`;
if(index == -1){
area1.innerHTML += "없습니다<br>"
}
else{
area1.innerHTML += `${index+1}번에 존재<br>`
}
}
5) 예제
1번 문제 )
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습문제5</title>
</head>
<body>
<h2>간이 계산기 만들기</h2>
첫번째 값 : <input type="number" id="num1"><br>
두번째 값 : <input type="number" id="num2"><br>
<input type="button" value="+" onclick="calculator(this.value);">
<input type="button" value="-" onclick="calculator(this.value);">
<input type="button" value="x" onclick="calculator(this.value);">
<input type="button" value="/" onclick="calculator(this.value);">
<input type="button" value="%" onclick="calculator(this.value);"> <br><br>
계산결과 : <span id="result"></span>
<hr>
<script src="test1.js"></script>
</body>
</html>
function calculator(a){
let num1 = document.querySelector("#num1").value;
let num2 = document.querySelector("#num2").value;
let result = document.querySelector("#result");
//switch문을 이용해 num1과 num2에대해 버튼에 따라 다른 연산을하도록
//(a) : 이벤트가 발생한 객체의value
switch(a){
case '+' : {result.innerHTML = (num1+num2)}; break;
case '-' : {result.innerHTML = (num1-num2)}; break;
case 'x' : {result.innerHTML = (num1*num2)}; break;
case '/' : {result.innerHTML = (num1/num2)}; break;
case '%' : {result.innerHTML = (num1%num2)}; break;
}
}
문제2)
<!DOCTYPE html>
<!-- webapp/20230323/imgex2.html -->
<html>
<head>
<meta charset="UTF-8">
<title>마우스 이벤트를 이용한 이미지 변경</title>
</head>
<body>
<table>
<tr><td align="center">
<!--onmouseover : 마우스를 버튼에 가져다 댈 때-->
<!--onmouseout : 마우스가 버튼에서 벗어나 있을 때 -->
<a href="#" onmouseover="mover(0)" onmouseout="mout(0)">
<img name="m0" src="../img/0_out.jpg"></a>
</td></tr>
<tr><td align="center">
<a href="#" onmouseover="mover(1)" onmouseout="mout(1)">
<img name="m1" src="../img/1_out.jpg"></a>
</td></tr>
<tr><td align="center">
<a href="#" onmouseover="mover(2)" onmouseout="mout(2)">
<img name="m2" src="../img/2_out.jpg"></a>
</td></tr>
</table>
<script src="test2.js"></script>
</body>
</html>
JS
function mover(a){//버튼에 마우스를 가져다 댈 때
//img태그 중 name이 ma인 태그 조회
let m = document.querySelector(`img[name=m${a}]`);
console.log(m)//확인용
//조회된 태그의 src(경로)를 밑에와같이 변경
m.src = `../img/${a}_over.jpg`;
}
function mout(b){//버튼에서 벗어날 때
let m = document.querySelector(`img[name=m${b}]`);
console.log(m)
m.src = `../img/${b}_out.jpg`;
}
문제3) 달력생성
<!DOCTYPE html>
<!-- webapp/20230324/exam1.html -->
<html>
<head>
<meta charset="UTF-8">
<title>달력 출력하기</title>
<style type="text/css">
table { width:100%; border-collapse: collapse;}
th,td {border : 3px solid #bcbcbc; text-align: center; padding: 8px;}
th {background-color: #e2e2e2; color:#111111;}
td {background-color: #f2f2f2;}
caption {color:#111111; font-size: 20px; background-color: #ffffff;}
.text-red {color:red;}
.text-blue {color:blue;}
</style>
</head>
<body>
<select id="y"><option>2023</option><option>2024</option>
<option>2025</option><option>2026</option>
</select>
<select id="m"><option value="1">1월</option><option value="2">2월</option>
<option value="3">3월</option><option value="4">4월</option>
<option value="5">5월</option><option value="6">6월</option>
<option value="7">7월</option><option value="8">8월</option>
<option value="9">9월</option><option value="10">10월</option>
<option value="11">11월</option><option value="12">12월</option>
</select>
<input type="button" value="달력보기" onclick="show_cal()"><br>
<span id="cal"></span>
<script src="test3.js"></script>
</body></html>
function show_cal(){
let y = document.querySelector("#y").value;
console.log(y)//선택된option이 나옴
let m = document.querySelector("#m").value;
console.log(m)//선택된option이 나옴 //month-1을 해줘야 해당달이들어감
let day=1;
let date = new Date(y,m-1,day);
//Date방식의 month : 0~11
let date2 = new Date(y,m,0);
//해당 달+1 세팅 후 date를 0 으로설정 시
//해당달의 마지막날짜가 세팅 됨
let lastDay = date2.getDate();
let a = `<table><tr> <caption>${y}년${m}월</caption>`
a+=`<th class='text-red'>일</th><th>월</th><th>화</th><th>수</th>
<th>목</th><th>금</th><th class='text-blue'>토</th></tr> <tr>`;
let week = date.getDay();
for( i=week ; day<=lastDay ; i++ ){
if(day==1){
for(j=0 ; j<i;j++){
a+=`<td></td>`
}
if(i==6){ //토요일이라면 행을 바꿔주고 class text-blue지정
a+=`<td class='text-blue' >${day}</td></tr><tr>`
}
else if(i==0){ //일요일이라면 class text-red지정
a+=`<td class='text-red' >${day}</td>`
}
else{ //모두아니라면 그냥 날짜만 찍어준다
a+=`<td>${day}</td>`
}
day++; //날짜++
}
//여기까지는 해당 월의 1일만 해당하는 문장들임
//⬇⬇⬇ 날짜가 1일이 아닌 경우
else{
if(i%7==0){ //일요일 : 0 7 14 21 28 -> 7로나눈 나머지는 0
a+=`</tr><tr><td class='text-red'>${day}</td>`
}
else if((i+1)%7==0){ //토욜 : 6 13 20 ... -> +1을 해주고 %7을하면 0이 됨
a+=`<td class='text-blue'>${day}</td>`
}
else{
a+=`<td>${day}</td>`
}
day++;
}
}
for(i=date2.getDay() ; i<6 ;i++){
a+= "<td></td>"
}
//해당월의 마지막날짜의 요일 이용
//칸을 맞추기위해(수요일이면 토요일까지의 달력을 빈칸으로채우는 것)
a+= "</tr></table>"
let cal = document.querySelector("#cal");
cal.innerHTML += a; //쿼리를 전부다 cal.innerHTMl에 넣기
}
문제4) 지정년도의 전체달력 출력
(문제3의 내용에서 조금만 더 생각이 필요함!!1)
<!DOCTYPE html>
<!-- /webapp/test3/test1.html -->
<html><head>
<meta charset="UTF-8">
<title>달력 출력하기</title>
<style type="text/css">
.mon { width:100%; border-collapse: collapse;table-layout: fixed;}
th.mon,td.mon {border : 3px solid #bcbcbc;
text-align: center; padding: 8px;}
th.mon {background-color: #e2e2e2; color:#111111;}
td.mon {background-color: #f2f2f2;}
caption {color:#111111; font-size: 20px;
background-color: #ffffff;}
.text-red { color : red;}
.text-blue { color : blue;}
</style>
</head><body>
<select id="y">
<option>2020</option><option>2021</option><option>2022</option>
<option">2023</option><option>2024</option>
<option selected="selected">2025</option><option>2026</option>
</select>
<input type="button" value="달력보기" onclick="show_cal()">
<br><span id="cal"></span>
<script src="test4.js"></script>
</body></html>
function show_cal(){
let y = document.querySelector("#y").value;
//12개의 월을 담아넣을 테이블 생성
let a = `<table class='mon'><caption>${y}년</caption><tr>`;
for(let d=0 ;d<=11 ;d++){//Date의 월(month) : 0~11
let date = new Date(y,d,1);
//d월의 마지막날짜를 구하기위함
let date2 = new Date(y,(d+1),0);
let lastday = date2.getDate();
//테이블의 n행n열에 테이블을 생성함
a+= `<td><table class='mon'><caption>${d+1}월</caption>`;
a += `<th class='mon text-red'>일</th><th class='mon'>월</th><th class='mon'>화</th><th class='mon'>수</th>
<th class='mon'>목</th><th class='mon'>금</th><th class='mon text-blue'>토</th></tr><tr>`;
let day = 1;
for( i=date.getDay() ; day<=lastday ; i++ ){
if(day==1){
for(j=0 ; j<i;j++){
a+=`<td class='mon'></td>`
}
if(i==6){ //토요일이라면 행을 바꿔주고 class text-blue지정
a+=`<td class='mon text-blue' >${day}</td></tr><tr>`
}
else if(i==0){ //일요일이라면 class text-red지정
a+=`<td class='mon text-red' >${day}</td>`
}
else{ //모두아니라면 그냥 날짜만 찍어준다
a+=`<td class='mon'>${day}</td>`
}
day++; //날짜++
}
else{
if(i%7==0){ //일요일 : 0 7 14 21 28 -> 7로나눈 나머지는 0
a+=`</tr><tr><td class='mon text-red'>${day}</td>`
}
else if((i+1)%7==0){ //토욜 : 6 13 20 ... -> +1을 해주고 %7을하면 0이 됨
a+=`<td class='mon text-blue'>${day}</td>`
}
else{
a+=`<td class='mon'>${day}</td>`
}
day++;
}
}
for(i=date2.getDay() ; i<6 ;i++){
a+= "<td class='mon'></td>"
} //칸을 맞추기위해(수요일이면 토요일까지의 달력을 빈칸으로채우는 것)
a+= `</table></td>` //해당월을 날짜를 모두출력했다면 테이블을 닫고 다음 열로넘어감
//4월 8 월 12월의경우 : 행을 바꾼다!!
if ((d+1)%4==0){a+=`</tr><tr>`}
}
a+=`</table>`;
document.querySelector("#cal").innerHTML = a;
}
'JavaScript' 카테고리의 다른 글
부트캠프39일(jquery{요소선택자,필터링,요소탐색,예제}) (0) | 2025.03.28 |
---|---|
부트캠프38일차 (게임들 , jquery , 예제) (0) | 2025.03.27 |
부트캠프37일차(BOM,game) (0) | 2025.03.26 |
부트캠프34일차(JS[요소조회출력, 문자열,Math, 조건문]) (0) | 2025.03.20 |
부트캠프33일차(JS) (0) | 2025.03.19 |