void = return값이 없음
o Date객체 세팅
const someday = new Date();
someday.setFullYear(1989, 5, 8); //1989년 6월 8일>>실제 Month값은 6으로 인식하기 때문에 입력값을 -1해야
//Month값은 0-11
someday.setHours(24);
someday.setMinutes(59);
document.writeln(someday.getFullYear());//1989
document.writeln(someday.getMonth());//5
document.writeln(someday.getDate());//8 -> 9
document.writeln(someday.getHours());// date+1 && hours 0
document.writeln(someday.getMinutes());//59
const days=["일","월","화","수","목","금","토"];
document.writeln(days[someday.getDay()]);//금
const d = new Date();
d.setDate(someday.getDate() + 10 );
//d변수에서 가져온 Date값을 설정->someday변수에서 가져온 Date값(9)에서 10일 더하기
document.writeln(d.getDate()); //19
d.setFullYear(someday.getFullYear() - 3 );
//d변수에서 가져온 FullYear값을 설정하자->someday변수에서 가져온 FullYear 값(1989)에서 -3
document.writeln(d.getFullYear());
o

/*
객체(Object)
-Object = 멤버변수+멤버함수로 구성
(.을 눌렀을 때 나오는 것들)
-멤버변수, Property, Attribute, field, column
-멤버함수, method, function
-객체명.멤버변수
-객체명.멤버함수()
*/
//1. Math 객체
//document.writein(Math.PI); //Math객체의 멤버변수 파이값
//document.writeln(Math.abs(-3)); //Math객체의 멤버함수 절댓값
//2. Number객체
//document.writeln(Number("5")); //"5" -> 5 문자열을 숫자열로 변환하는 멤버함수
//document.writeln(Number("8.9")); //"8.9" -> 8.9
//3. Date 객체
//const d = new Date();
////////////////////////////////////////////////
//4. window객체 - 브라우저와 관련한 다양한 기능 제공
//->객체명을 생략가능
//1) alert() 브라우저에서 경고창 출력 시 사용(확인버튼)
//window.alert(123);
//alert();로도 사용가능
/*
alert("KOREA");
alert("\"");
alert("'");
alert("'");
alert("\\");
*/
// alert("서울\n제주\n\n부산");//경고창에서는 <br>사용금지, \n으로 줄바꿈
//2) confirm() 경고창 (확인/취소 버튼)
// ->boolean값으로 반환
//confirm("영구히 삭제됩니다\n지울까요?");//window객체명 생략가능
/*
let flag = confirm("영구히 삭제됩니다\n지울까요?");
if(flag) {
alert(flag);//확인키를 누르면 true를 내용으로 하는 경고창
alert("성공");
}else{
alert(flag);//취소키를 누르면 false를 내용으로 하는 경고창
alert("실패");
}
*/
//3) 새창 띄우기
//open();
//close() 창닫기
//4) 인쇄창 띄우기
//print();
//5) setInterval()과 setTimeout()
/*
-주어진 시간에 따라 자동으로 함수 호출
-시간 : 1 second = 1000 milliseconds
- new version
setInterval(함수명, 시간) : 주기적으로 함수 호출
setTimeout(함수명, 시간) : 한번만 호출
- old version
setInterval("함수명()", 시간)
setTimeout("함수명()", 시간)
-시간해제 : clearInterval(), clearTimeout()
*/
function hello(){
alert("안녕하세요");
}//hello() end
//setInterval(hello, 3000);
//setTimeout(hello, 3000);
/* 재귀적 함수 호출 관계를 이용해 3초마다 주기적으로 hello함수 호출
function hello(){
setTimeout(hello, 3000);
}//hello() end
//setInterval과 같은 결과
*/
//5. screen 객체
//사용자 device의 해상도 확인
//alert(screen.width);
//alert(screen.height);
//6. location
//새로고침
//location.reload(); //현재페이지 새로고침
//""내의 링크로 페이지 이동
//-> location.href="URL 또는 페이지명"
//-> location="URL 또는 페이지명"
//7. history
//뒤로, 앞으로
//history.back();
//history.forward();
history.go(-2); //뒤로 뒤로
o 전역변수와 지역변수
//참조 https://www.w3schools.com/js/js_scope.asp
/*
변수의 종류
- 지역변수(local variable)
> function 함수 내에 선언된 변수는 함수내에서만 사용 가능
> 한 지역; 중괄호 내
- 전역변수(global variable)
> function함수 외부에서 선언된 변수로 모든 함수내에서 그 값 공유
> 선언한 시점부터 전체적으로 쓸 수 있음
*/
<input type = "button" value="SCOPE1" onclick="alert('오필승')">
<input type = "button" value="SCOPE2" onclick="alert('코리아')">
//html형식 내에서 바로 이벤트 시 문구 출력되게
<hr>
<input type = "button" value="SCOPE3" onclick="test3()">
<input type = "button" value="SCOPE4" onclick="test4()">
//이벤트 시 자바스크립트 함수를 호출하여 문구 출력되게
<script>
let one = "하나"; //전역변수, function 밖이라면 어디서든 선언 가능
function test3() {
alert("one : " + one);
alert("two : " + two);
alert("three : " + three);
let uid = "아이티윌"; // 지역변수
alert(uid);
}//test3 end
let two = "둘";
function test4() {
let two="두번째";//전역변수로 선언된 two와 같은 변수명이나 호출 시 오류뜨지 않음>>지역변수의 우선순위가 더 높다
alert(two);
alert("one : " + one);
alert("two : " + two);
alert("three : " + three);
alert(uid);
}//test4 end
let three = "셋";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<h3>디지털시계</h3>
<div id = "clock"></div>
<hr>
<input type="button" value="start" onclick="showtime();">//시계를 띄우는 버튼
<input type="button" value="stop" onclick="killtime();">//시계를 멈추는 버튼
<script>
//showtime(); 화면 실행시 바로 시계 뜨게
function showtime() {
const d = new Date();
let today = "";
~이하 today에 들어가는 시계데이터 불러오기~
document.getElementById("clock").innerText = today;
//1초후에 showtime함수 호출
timer = setTimeout(showtime, 1000);
//'1초후에 showtime함수 호출'하는 것을 전역변수 timer에 넣음
}
//1초마다 변화초가 반영되는 디지털시계 완성
//showtime의 today는 지역변수이므로 다른 함수인 killtime에서 접근 불가능 >> 전역변수 선언 필요
let timer;//따라서 전역변수 timer선언, 자바와 달리 변수 타입에 구애x
function killtime() {
clearTimeout(timer);
}//시계를 멈추는 함수
////////////////////////////////////////////////////////////////////
o 오디오와 이미지 (+리스트 링크) 띄우기
o js파일 import
<body>
<div style="text-align: center;">
<h3>음악목록</h3>
<img src="../../music/gangnamstyle.jpg" id = "poster" width = "300px" height="250px">
<br><br>
<audio src="../../music/gangnamstyle.mp3" id = "audio1" controls></audio>
</div>
<div style="margin: auto; width: 50%;">
<ol>
<li><a href="javascript:loadmusic('../../music/genie.jpg', '../../music/genie.mp3')">소원을 말해봐</a></li>
<li><a href="javascript:loadmusic('../../music/sheis.jpg', '../../music/sheis.mp3')">그녀가 처음 울던날</a></li>
<li><a href="javascript:loadmusic('../../music/candy.jpg', '../../music/candy.mp3')">내귀에 캔디</a></li>
<li><a href="javascript:loadmusic('../../music/gangnamstyle.jpg', '../../music/gangnamstyle.mp3')">강남스타일</a></li>
</ol>
</div>
<script>
function loadmusic(jpg, mp3) {
//alert("#" + jpg + "#");
//alert("#" + mp3 + "#");
let poster = document.getElementById("poster");
let audio1 = document.getElementById("audio1");
//alert(poster);
//alert(audio1); //alert를 심어 놓아 어디서 어떻게 흘러가고 있는지 확인
poster.src = jpg;
audio1.src = mp3;
audio1.play();
}//loadmusic() end
</script>
////////////////////////////////////////////////////////////////////////////////
<!--html-->
<head>
<title>06_js파일.html</title>
<style>
</style>
<!--.js파일 import-->
<script src="myscript.js"></script>
<!--경로가 같기 때문에 파일명만 언급-->
</head>
<body>
<h3>js파일</h3>
<script>
alert(hap(5, 2));
alert(diff(7, 3));
alert(leap(2023));
</script>
------------------------------------------------------------------------------
/* import되는 myscript.js */
//두 수 사이의 합을 반환
function hap(a, b) {
if(a>b) {
let tmp = a; a=b; b=tmp;
}
let sum=0;
for(let n=a; n<=b; n++){
sum += n;
}
return sum;
}
//두 수 사이의 차이 반환(절대값)
function diff(a, b) {
return Math.abs(a-b);
}
//윤년, 평년 반환
function leap(year) {
if(year % 4 == 0 && year % 100 !=0 || year % 400 == 0) {
return true;
}else{
return false;
}
}
/////////////////////////////////////////////////////////////////////
<body onload="alert('불러오기완료')">
<h3>이벤트</h3>
<form name="myform" id="myform" action="ok.jsp" onsubmit="return true">
<!--
onsubmit이벤트는 해당 폼(myform)이 서버로 전송될 때
return값이 true이면 해당폼이 전송된다
return값이 false면 전송되지 않는다
-->
<input type="button" value="버튼1" onclick="alert('버튼1 클릭')">
<hr>
<input type="button"
value="아이티윌"
onclick="location.href='https://www.itwill.co.kr/'">
<!--onclick-"XXX" 클릭 시 XXX-->
<hr>
<input type="button"
value="마우스"
onmouseover="alert('마우스오버')"
onmouseout="alert('마우스아웃')">
<hr>
<input type="text" onkeydown="alert('keydown')">
<br>
<textarea rows="5" cols="10" onkeydown="alert('키보드누름')"></textarea>
<hr>
<select onchange="alert('목록변경')">
<option>서울</option>
<option selected>제주</option>
<option>부산</option>
</select>
<hr>
<!--<input type="text" onfocus="alert('커서인')">-->
<hr>
<!--서버로 해당 폼이 전송될 때 발생하는 이벤트 onsubmit(리턴값 있음) -->
<!--form에 작성-->
<!-- 폼을 서버로 전송하는 컨트롤 요소들 -->
<input type="submit" value="전송1">
<button>전송2</button><!--기본속성이 submit-->
<input type="image" src="../../images/angel.png"><!--기본속성이 submit-->
</form>
<script>
/*
- 자바스크립트는 주로 이벤트를 발생시킨 후 함수를 호출함으로써 실행한다
- 기본 이벤트의 종류
onchange 다른 객체로 바뀌었을때
onclick 마우스 클릭했을때
onmouseover 마우스가 올려졌을때
onmouseout 마우스가 나갔을때
onkeydown 키보드를 눌렀을때
onload 문서를 불러오는 작업이 끝났을 때 >> body에 입력
*/
</script>
//////////////////////////////////////////////////////////////////
<h3>마우스이벤트</h3>
<table border="1px">
<tr>
<th onmouseover="show('r')">라이언</th>
<th onmouseover="show('n')">네오</th>
<th onmouseover="show('j')">제이지</th>
</tr>
<tr>
<td colspan="3" >
<div id = "ryan" style="display: block;">
<img src="../../images/k7.png">
</div>
<div id = "neo" style="display: none;">
<img src="../../images/k5.png">
</div>
<div id = "jayg" style="display: none;">
<img src="../../images/k3.png">
</div>
</td>
</tr>
</table>
<script>
//마우스오버에 따른 이미지 보여주기 함수
function show(kind) {
switch(kind) {
case "r":
document.getElementById("ryan").style.display="block";
document.getElementById("neo").style.display="none";
document.getElementById("jayg").style.display="none";
break;
case "n":
document.getElementById("ryan").style.display="none";
document.getElementById("neo").style.display="block";
document.getElementById("jayg").style.display="none";
break;
case "j":
document.getElementById("ryan").style.display="none";
document.getElementById("neo").style.display="none";
document.getElementById("jayg").style.display="block";
break;
}
}//show() end
</script>
'수업노트' 카테고리의 다른 글
| 23.2.17(금) (0) | 2023.02.17 |
|---|---|
| 배열메소드 (0) | 2023.02.17 |
| 23.2.15(수) (0) | 2023.02.16 |
| 23.2.14(화) (0) | 2023.02.14 |
| 23.2.13 (월) (0) | 2023.02.13 |