◐date.html
-날짜
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
document.addEventListener('DOMContentLoaded', function(){
//DOMContentLoaded : html 문서를 브라우저가 다 읽고 나면,
//document.addEventListener(이벤트 이름, 이벤트리스너);
//DOMContentLoaded : content가 읽혀졌을때,
//Dom(Document Object Model) : 문서 객체 모델, 문서 객체를 조햅해서 만든
// 전체적인 형태를 의미
//function : 이벤트 핸들러, 이벤트 리스너, 콜백함수
//이벤트 : 마우스클릭, 드래그 , .....
//이벤트리스너(eventListener) : 이벤트 핸들러, 이벤트가 실행될 때 호출되는 콜백함수
//콜백함수 : 함수를 매개변수로 사용하는 것을 의미
// let, const , var(불명확)
//const : 상수(자바final)
const date = new Date();
let arr = document.querySelectorAll('h1');
//querySelector - 하나만
//querySelectorAll - 전체
//querySelector( ) : .(클래스) #(아이디) 태그
arr[0].textContent = date.getFullYear + '년'; // innerHTML
//= : 오른쪽의 결과를 먼저실행하고 왼쪽에 담는다.
arr[1].textContent = date.getMonth() + 1 + '월';
arr[2].textContent = date.getDay() + 1 + '일';
let week = date.getDay(); //요일을 숫자로 읽어옴
let dayOfWeek = '';
switch(week){
case 0 : dayOfWeek = '일요일'; break;
case 1 : dayOfWeek = '월요일'; break;
case 2: dayOfWeek = '화요일'; break;
case 3 : dayOfWeek = '수요일'; break;
case 4 : dayOfWeek = '목요일'; break;
case 5 : dayOfWeek = '금요일'; break;
case 6 : dayOfWeek = '토요일'; break;
}
arr[3].textContent = dayOfWeek;
arr[4].textContent = date.getHours() + '시';
arr[5].textContent = date.getMinutes() + '분';
arr[6].textContent = date.getSeconds() + '초';
});
</script>
</head>
<body>
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
<!-- <h1 class="year"></h1>
<h1 class="month"></h1>
<h1 class="day"></h1>
<h1 class="week"></h1>
<h1 class="hour"></h1>
<h1 class="minute"></h1>
<h1 class="second"></h1> -->
</body>
</html>
◐ttiArr.html
-12지에 대한 것
<ttiArr.html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// window.onload = function() { }
document.addEventListener('DOMContentLoaded', function(){
const h1 = document.querySelector('#tti');
//안바뀌고 싶어서 const를 사용
let birthYear = number(prompt('태어난 연도를 입력하세요', '네자리 연도로 입력하세요'))
let ttiArr = '원숭이,닭,개,돼지,쥐,소,호랑이,토끼,용,뱀,말,양'.split(','); // ,로 구분해서 배열로 저장
//값을 넣을때, 타입이 정해진다.
});
</script>
</head>
<body>
<h1 id="tti"></h1>
</body>
</html>
1. 함수 : 코드의 집합
자바스크립트에서는 함수도 하나의 자료라서 변수에 할당할 수 있고,
함수를 함수의 매개변수로 전달해서 화룡할 수 있음
자바스크립트는 함수와 변수가 굉장히 유연함
2. 함수를 사용하는 목적
- 반복되는 코드를 한 번만 정의해 놓고 필요할 때마다 호출해서 사용(재사용성)
- 기능별로 분류를 함으로써 모듈화 가능
- 유지보수가 수월
- 가독성이 좋아짐
3. 함수 용어
함수 호출 : 함수를 사용하는 것
매개변수 : 함수를 호출할 때 괄호 내부에 여러 가지 자료를 넣을
수 있는데 이 때 이 자료
리턴값 : 함수를 호출해서 최종적으로 나오는 결과 반환
4. 함수
1) 익명 함수 : 순차적인 코드 실행에서 코드가 해당 줄을 읽을 때 생성
함수를 출력할 때 별다른 이름이 붙어 있지 않은 함수(함수 이름이 없음)
그래서 변수에 결과를 담는다.
function(){} === () => {} 함수명이 없는 것 : 익명함수(화살표함수)
똑같지만, 이름이 없느냐 있느냐 차이.
형식)
function(){
실행할 문장
}
function(매개변수,.....){ // 매개변수 - 외부로부터 전달 받은 자료를 담는 변수
실행할 문장
}
const 함수명 = function(){ 실행할 문장 }
함수명() => 함수를 호출
함수명(매개변수에 전달할 값, 값,...)
2) 선언적 함수 : 순차적인 코드 실행이 일어나기 전에 생성
같은 블록이라면 어디에서든 함수를 호출해도 됨
선언적 함수를 생성하기 전에 함수를 호출해도 함수가 이미 생성된
상태이므로 아무 문제가 없이 실행
함수의 이름이 있는 함수
형식)
function 함수명(){ 실행할 문장들 }
function 함수명(매개변수,....){
실행할 문장
실행할 문장
return 리턴값 // 함수를 호출한 부분으로 결과를 가지고 돌아간다.
}
함수명()
함수명(매개변수에 전달할 값, 값,...)
3) 화살표 함수 : 콜백함수(함수를 매개변수로 받는 함수)에 주로 사용
익명적 함수를 () => { }로 변경
익명: function(){
실행할 문장
}
화살표 : () => { 실행할 문장 }
비교)자바 : '람다식'이라 부름 () -> {실행 문장} : 함수명을 생략
익명 : function(매개변수,.....){ // 매개변수 - 외부로부터 전달 받은 자료를 담는 변수
실행할 문장
}
화살표 : (매개변수,....) => { 실행할 문장 }
4) 콜백함수 : 자바스크립트는 함수도 하나의 자료형이므로 매개변수로 전달할 수 있음
이렇게 매개변수로 전달하는 함수를 callback 함수라고 함
5) 타이머 함수
타이머 함수
setTimeout(실행할함수, 시간) : '한 번' 실행(주어진 시간이 되면 '실행할함수'를 호출)
setInterval(실행할함수, 시간) : '지속적'으로 실행(주어진 '시간'이될때마다 지속적으로 '실행할 함수'를 호출)
ex)시간되면 자동으로 넘어가는 기능같은 경우...
타이머 종료
clearTimeout(타이머_id) : setTimeout()함수로 설정한 타이머를 제거
clearInterval(타이머_id) : setInterval()함수로 설정한 타이머를 제거
* setTimeout(함수, 시간) : 시간 후에 앞에 있는 함수를 실행, 한 번만 실행
시간 : 초단위 사용(1000 - 1초)
setTimeout(함수,시간)
setTimeout(function(){ },시간)
setTimeout(()=>{ },시간)
setTimeout(()=>{
secondDiv.appendChild(moveText)
}, 2000)
◐function.html
-선언적함수
-익명적함수
-화살표함수
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
/* 화살표함수,콜백함수
//document.addEventListener('DOMContentLoaded', () => {});
//document.addEbentListener('DOMContentLoaded' function(){});
*/
//선언적 함수
function add(num1, num2){
document.write('<h1> ' + (num1 + num2) + '</h1>');
document.write('<hr>')
}
//익명적 함수
const add1 = function(num1, num2){
document.write('<h1> ' + (num1 + num2) + '</h1>');
document.write('<hr>')
}
//화살표 함수
const add2 = (num1, num2) => {
document.write('<h1> ' + (num1 + num2) + '</h1>');
document.write('<hr>')
}
add(10,20);
add1(30,40);
add2(50,60);
</script>
</head>
<body>
</body>
</html>
◐timer.html
-타이머
◐function2.html
-아이디입력체크
-이름입력체크
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 비어있는 것에 대한 여부를 함수로 호출-->
<script>
let testfunction = function(){
//let name = document.querySelector('#id'); //type=text
let uid = document.querySelector('[name=uid]');
let uname = document.querySelector('[name=uname]');
//#id == name=uid ???????????????
//입력 유무 체크
//uid.value.length === 0 (글자길이체크)
if(uid.value === ""){ //uid에 글자가 입력되어 있지 않으면
// !(uid.value.length >= 3 && uid.value.length <= 8), 글자길이 체크
// uid.value ==""; uid안의 글자를 지우기
alert('아이디를 입력하세요...');
uid.focus(); //커서를 uud에 놓겠다.
return false;
}
if(uname.value === ""){
alert('이름을 입력하세요...')
uname.focus(); //커서를 이곳에 놓기
return false;
}
return true;
}
</script>
</head>
<body>
<form action="" method="post" name="member" onsubmit="return testfunction()">
<!--
onsubmit : submit이 눌려지면 testfunction() 실행해줘
true면 action을 실행 (action 다른데서 처리)
faslse면 0값
-->
아이디 : <input type="text" name="uid" id="id"><br>
이름 : <input type="text" name="uname" id="name"><br>
<input type="submit" value="전송">
</form>
</body>
</html>
◐function3.html
-아이디입력체크
-이름입력체크
-radio태그 입력체크
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
/*
required : 를 사용한다면, 코딩할일이 줄어듭니다.
placehold : 안내문구없이 정리가능
html에서 전송전에 자체적으로 정리되는 것들은 사용하는 것이 좋습니다.
*/
// 선언적
function checkfun (){
const uid = document.querySelector('[name=uid]');
// let uid = document.querySelector('[name=uid]');
// var uid = document.querySelector('[name=uid]');
const pwd = document.querySelector('[name=pwd]');
const birth = document.querySelectorAll('[name=birth]'); //배열로 저장
// 이렇게 사용하면 너무 길기떄문에 표현식?을 사요한다.
// let result = uid.value === "" || !(uid.value.lenhth>= 3 && uid.value.lenhth<=8)
if(uid.value === ""){
alert('아이디를 입력하세요');
uid.focus();
return false;
}
if(pwd.value === ""){
alert('비밀번호를 입력하세요');
pwd.focus();
return false;
}
//checked라는 것 사용
//radio는 true ,false를 리턴하는 것 같다.
//포커스 사용하지않기를 권장 - 실행되어버림
if(birth[0].checked === false && birth[1].checked === false){ //길이가 길면 변수로 빼서 사용하면 좋습니다.
alert("생일의 음력,양력을 체크하세요");
return false;
}
return true;
}
/*
//익명적
let checkfun = function(){
let uid = document.querySelector('[name=uid]');
let upwd = document.querySelector('[name=upwd]');
let ubirth = document.querySelector('[name=ubirth]');
//#id == name=uid ???????????????
//입력 유무 체크
//uid.value.length === 0 (글자길이체크)
if(uid.value === ""){ //uid에 글자가 입력되어 있지 않으면
// !(uid.value.length >= 3 && uid.value.length <= 8), 글자길이 체크
// uid.value ==""; uid안의 글자를 지우기
alert('아이디를 입력하세요...');
uid.focus(); //커서를 uud에 놓겠다.
return false;
}
if(upwd.value === ""){
alert('비밀번호을 입력하세요...')
upwd.focus(); //커서를 이곳에 놓기
return false;
}
if(document.getElementsByName(b1)=== ""){
alert('생일을 체크하세요...')
ubirth.focus(); //커서를 이곳에 놓기
return false;
}
return true;
}
*/
</script>
</head>
<body>
<form action=" " method="post" onsubmit="return checkfun()" >
<!-- action : 넘길 값을 받을 페이지입력
ex) form action="..member.jsp"
-->
아이디 <input type="text" name="uid"><br>
비밀번호 <input type="password" name="pwd"><br>
생년월일 <input type="radio" name="birth" value="b1">양
<input type="radio" name="birth" value="b2">음
<br>
<input type="submit" value="가입">
<input type="reset" value="다시쓰기">
<!-- radio는 name은 같고 value는 달라야합니다. -->
<!-- radio나 check박스는 배열로 받아야 합니다.-->
</form>
</body>
</html>
'4.VisualStudioCode > 2).VisualStudioCode_개념 및 실습' 카테고리의 다른 글
VisualStudioCode_Day_10 (0) | 2024.03.02 |
---|---|
VisualStudioCode_Day_09 (0) | 2024.03.02 |
VisualStudioCode_Day_07 (2) | 2024.02.26 |
VisualStudioCode_Day_06 (1) | 2024.02.23 |
VisualStudioCode_Day_05 (0) | 2024.02.23 |