5월 ~ 7월) 웹/web

47Day - 41_event_handle/ 42_event_this/ 43_event_default/ 44_event_propagation/ 45_event_listener/ 46_event_dom/ 47_form_action & 47_form_submit/ 48_subimt_form & 48_submit_action/ 49_exception/ 50_cookie

첼로그 2023. 6. 12. 20:11

41_event_handle

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
	<h1>이벤트(Event) - 이벤트 처리</h1>
	<hr>
	<p>이벤트 : 태그(박스모델 - Element 객체)에서 발생되는 다양한 사건</p>
	<p>이벤트 처리(Event Handle) : 태그에서 발생된 이벤트에 대한 처리를 자바스크립트 
	명령으로 작성하여 실행</p>
	<p>1.태그의 이벤트 리스너 속성(onXXX)의 속성값으로 이벤트 처리 명령 작성
	- 태그에서 이벤트 리스너 속성의 이벤트가 발생될 속성값으로 설정된 명령 실행</p>
	<p>2.태그를 검색하여 Element 객체로 제공받아 Element 객체의 이벤트 리스너 속성에 이벤트 
	처리 함수 등록 - 태그에서 이벤트 리스너 속성의 이벤트가 발생될 경우 이벤트 처리 함수 호출</p>
	<p>3.태그를 검색하여 Element 객체로 제공받아 addEventListener() 메소드를 호출하여 이벤트
	처리 함수 등록 - 태그에서 addEventListener() 메소드의 이벤트가 발생될 경우 이벤트 처리 함수 호출</p>
	<hr>
	<!-- <button type="button" onclick="alert('이벤트 처리 명령 실행-1');">버튼-1</button> -->
	<!-- 이벤트 처리 명령으로 이벤트 처리 함수 호출 -->
	<button type="button" onclick="eventHandle();">버튼-1</button>
	<button type="button" id="eventBtn2">버튼-2</button>
	<button type="button" id="eventBtn3">버튼-3</button>
	
	<script type="text/javascript">
	
	// 방법 1)
	//이벤트 처리 함수
	function eventHandle() {
		alert('이벤트 처리 명령 실행-1');
	}
	
	// 방법 2)
	//Element 객체의 이벤트 리스너 속성에 이벤트 처리 함수 저장(등록)
	document.getElementById("eventBtn2").onclick=function() {
		alert('이벤트 처리 명령 실행-2');
	}
	
	// 방법 3)
	//Node.addEventListener(eventName, callback[, useCapture]) : Node(Element) 객체에서
	//이벤트(eventName)가 발생될 경우 콜백함수(이벤트 처리 함수)를 호출하는 메소드
	document.getElementById("eventBtn3").addEventListener("click", function(e) {
		alert('이벤트 처리 명령 실행-3');
	});
	</script>
</body>
</html>

 


 


 


42_event_this

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
<style type="text/css">
#displayDiv {
	width: 600px;
	font-size: 2em;
	font-weight: bold;
	text-align: center;
	border: 1px solid red;
}

ul li {
	width: 400px;
	margin: 10px;
	text-align: center;
	font-size: 1.5em;
	font-weight: bold;
	border: 1px solid blue;
	list-style-type: none;
}
</style>
</head>
<body>
	<h1>이벤트(Event) - this</h1>
	<hr>
	<p>이벤트 처리 함수에서 이벤트가 발생된 태그(Element 객체)를 표현하기 위해 this 키워드 사용</p>
	<hr>
	<div id="displayDiv">이벤트 처리</div>
	<hr>
	<ul>
		<li>메뉴-1</li>
		<li>메뉴-2</li>
		<li>메뉴-3</li>
	</ul>
	
	<script type="text/javascript">
	document.getElementById("displayDiv").onclick=function() {
		//alert("태그에서 클릭 이벤트가 발생 되었습니다.");
		
		//Node(Element) 객체의 프로퍼티로 태그의 속성을 표현 가능
		//document.getElementById("displayDiv").style="color: green;"; //div 태그의 style 속성값 변경
		
		//this 키워드에는 이벤트가 발생된 태그의 Node(Element) 객체가 자동 저장
		this.style="color: green;"; //div 태그의 style 속성값 변경
	}
	
	var liList=document.getElementsByTagName("li");
	
	/*
	liList.item(0).onclick=function() {
		//liList.item(0).style="color: orange;";
		this.style="color: orange;";
	}
	
	liList.item(1).onclick=function() {
		//liList.item(1).style="color: orange;";
		this.style="color: orange;";
	}
	
	liList.item(2).onclick=function() {
		//liList.item(2).style="color: orange;";
		this.style="color: orange;";
	}
	*/
	
	for(i=0;i<liList.length;i++) { //i 변수에 3이 저장되면 반복문 종료
		//NodeList 객체에 저장된 모든 Node(Element) 객체의 이벤트 리스너 속성에 이벤트 처리 함수 등록
		// > 이벤트 처리 함수는 Node(Element) 객체에서 이벤트가 발생되면 호출되어 실행
		liList.item(i).onclick=function() {
			//반복문이 종료된 후 이벤트가 발생될 경우에 실행되는 명령
			//liList.item(i).style="color: orange;"; //liList.item(3) >> null
			
			// this를 안쓰면 이벤트처리가 안됨 > this 는 이벤트 발생태그를 발생
			this.style="color: orange;";
		}
	}
	</script>	
</body>
</html>

 


 


 

 


43_event_default

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
	<h1>이벤트(Event) - 태그의 기본 이벤트 처리 기능</h1>
	<hr>
	<p>태그에는 특정 이벤트에 대한 처리 기능을 제공 - a 태그, input 태그, form 태그 등</p>
	<hr>
	<button type="button" id="btn">다음(Daum)으로 이동</button>
	<hr>
	<!-- a 태그는 click 이벤트가 발생될 경우 href 속성값으로 설정된 페이지로 이동 -->
	<a href="https://www.naver.com" id="naver"><button type="button">네이버(Naver)으로 이동</button></a>
	
	<script type="text/javascript">
	document.getElementById("btn").onclick=function() {
		location.href="https://www.daum.net";
	}
	
	document.getElementById("naver").onclick=function() {
		//event 객체 : 태그에서 발생된 이벤트 관련 정보를 저장한 객체
		// => 이벤트 처리 함수가 호출되면 자동 생성되며 이벤트 처리 함수가 종료되면 자동 소멸
		
		//event.preventDefault() : 태그에 설정된 기본 이벤트 명령을 취소하는 메소드
		event.preventDefault();
	}
	</script> 
</body>
</html>

 


 

네이버 이동 클릭시 > 반응없음.


*** 44_event_propagation

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
<style type="text/css">
div {
	border: 1px solid black;
	padding: 30px;
	text-align: center;
}

#red { background: red; }
#green { background: green; }
#blue { background: blue; }
</style>
</head>
<body>
	<h1>이벤트(Event) - 이벤트 전달(Event Propagation)</h1>
	<hr>
	<p>브라우저에서 발생된 이벤트는 window 객체에 먼저 도착하고 DOM Tree를 이용하여 이벤트가 발생된
	타겟 태그에 도착한 후 다시 반대 방향으로 이동하여 window 객체에 도착한 다음 이벤트 소멸</p>
	<p>이벤트가 흘러가는 과정을 캡쳐링 단계와 버블링 단계로 구분</p>
	<p>캡쳐링(Capturing) 단계 : 이벤트가 window 객체로부터 타겟 객체(이벤트가 발생된 태그)까지
	모든 객체에 이벤트가 전달되는 과정 - 이벤트가 거쳐간 객체에 등록된 이벤트 처리 함수가 호출</p>
	<p>버블링(Bubbling) 단계 : 이벤트가 타겟 객체(이벤트가 발생된 태그)로부터 window 객체까지
	모든 객체에 이벤트가 전달되는 과정 - 이벤트가 거쳐간 객체에 등록된 이벤트 처리 함수가 호출</p>
	<hr>
	<div id="red">
		<div id="green">
			<div id="blue"></div>
		</div>
	</div>
	
	<script type="text/javascript">
	document.getElementById("red").onclick=function() {
		location.href="https://www.daum.net";
		
		//event.stopPropagation() : 이벤트 전달을 중지하는 메소드
		event.stopPropagation(); // 버블링. 흐름정지 (중요!!)
	}
	
	document.getElementById("green").onclick=function() {
		location.href="https://www.naver.com";
		event.stopPropagation();
	}
	
	document.getElementById("blue").onclick=function() {
		location.href="https://www.google.com";
		event.stopPropagation();
	}
	</script>
</body>
</html>

 


 

빨강 &rarr; 다음 / 초록 &rarr; 네이버 / 파랑 &rarr; 구글 이동.

 


45_event_listener

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
<style type="text/css">
div {
	border: 1px solid black;
	padding: 30px;
	text-align: center;
}

#red { background: red; }
#green { background: green; }
</style>
</head>
<body>
	<h1>이벤트(Event) - 이벤트 전달(Event Propagation)</h1>
	<hr>
	<!-- 태그의 이벤트 리스너 속성값으로 다수의 이벤트 처리 함수 호출 가능 -->
	<button type="button" onclick="eventHandleOne(); eventHandleTwo();">이벤트 버튼-1</button>
	<button type="button" id="btn2">이벤트 버튼-2</button>
	<button type="button" id="btn3">이벤트 버튼-3</button>
	<hr>
	<div id="red">
		<div id="green"></div>
	</div>
	
	<script type="text/javascript">
	function eventHandleOne() {
		alert("eventHandleOne 함수의 명령 실행");
	}
	
	function eventHandleTwo() {
		alert("eventHandleTwo 함수의 명령 실행");
	}
	
	//Node(Element) 객체의 이벤트 리스너 속성에 이벤트 처리 함수 등록
	// => Node(Element) 객체의 이벤트 리스너 속성에는 하나의 이벤트 처리 함수만 등록 가능
	document.getElementById("btn2").onclick=eventHandleOne;
	document.getElementById("btn2").onclick=eventHandleTwo;
	
	//Node(Element) 객체로 addEventListener() 메소드를 호출하여 이벤트 처리 함수 등록
	// > Node(Element) 객체의 addEventListener() 메소드를 사용하면 다수의 이벤트 처리 함수 등록 가능
	document.getElementById("btn3").addEventListener("click", eventHandleOne);
	document.getElementById("btn3").addEventListener("click", eventHandleTwo);
	
	//Node.addEventListener(eventName, callback[, useCapture])를 이용하여 이벤트 처리 함수 등록
	// > addEventListener() 메소드를 호출할 때 useCapture 매개변수를 이용하면 캐쳐링 또는
	//버블링 단계에서 콜백함수를 호출하여 이벤트 처리 명령 실행 가능
	// > useCapture 매개변수에 [false]를 전달하면 버블링 단계에서 콜백함수를 호출하여 이벤트 처리
	//명령을 실행하고 [true]를 전달하면 캐쳐링 단계에서 콜백함수를 호출하여 이벤트 처리
	document.getElementById("red").addEventListener("click", function() {
		//event.currentTarget : 이벤트가 발생된 태그에 대한 Element 객체를 저장한 프로퍼티
		var tag=event.currentTarget.tagName; 
		var id=event.currentTarget.getAttribute("id"); 
		//event.type : 태그에서 발생된 이벤트를 저장한 프로퍼티
		alert("캡쳐링 단계 = "+tag+" 태그("+id+")에서 "+event.type+" 이벤트 발생");
	}, true);
	
	document.getElementById("green").addEventListener("click", function() {
		var tag=event.currentTarget.tagName; 
		var id=event.currentTarget.getAttribute("id"); 
		alert("버블링 단계 = "+tag+" 태그("+id+")에서 "+event.type+" 이벤트 발생");
		//event.stopPropagation();
	}, false);
	
	document.getElementById("red").addEventListener("click", function() {
		var tag=event.currentTarget.tagName; 
		var id=event.currentTarget.getAttribute("id"); 
		alert("버블링 단계 = "+tag+" 태그("+id+")에서 "+event.type+" 이벤트 발생");
	}, false);
	</script>
</body>
</html>

 


 

이벤트 버튼 - 1 클릭

 

이벤트 버튼 - 2 클릭

 

이벤트 버튼 - 3 클릭

 

빨간네모 클릭

 

초록네모 클릭시

 


46_event_dom

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
<style type="text/css">
#itemListDiv div {
	margin: 5px;
}
</style>
</head>
<body>
	<h1>이벤트(Event) - DHTML</h1>
	<hr>
	<p>DHTML(Dynamic HTML) : 브라우저에서 이벤트가 발생될 경우 브라우저에 출력된 태그를
	변경하여 동적인 페이지 제공하는 기능</p>
	<hr>
	<button type="button" id="addBtn">아이템 추가</button>
	<div id="itemListDiv"></div>
	
	<script type="text/javascript">
	//태그를 구분하기 위한 값이 저장되는 변수
	var count=0;
	
	document.getElementById("addBtn").onclick=function() {
		count++;
		
		var newItem=document.createElement("div"); //<div></div>
		newItem.setAttribute("id", "item_"+count); //<div id="item_XXX"></div>
	
		var html="아이템["+count+"]&nbsp;&nbsp;<button type='button' onclick='removeItem("+count+");'>삭제</button>";
	
		newItem.innerHTML=html; //<div id="item_XXX">아이템[XXX][삭제]</div>
		
		//div 태그(itemListDiv)의 마지막 자식태그로 생성된 태그를 배치 - 출력
		document.getElementById("itemListDiv").appendChild(newItem);
	}
	
	//태그를 삭제하는 함수 - 매개변수로 태그를 구분할 수 있는 값을 전달받아 저장
	function removeItem(cnt) {
		//alert(cnt);
		
		var removeE=document.getElementById("item_"+cnt);
		document.getElementById("itemListDiv").removeChild(removeE);
	}
	</script> 
</body>
</html>

 


 

[아이템 추가] 클릭시

 

[삭제] 클릭시

 


47_form_action 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
	<h1>form 태그 관련 이벤트 - 처리페이지</h1>
	<hr>
</body>
</html>

 

& *** 47_form_submit

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
	<h1>form 태그 관련 이벤트 - 입력페이지</h1>
	<hr>
	<p>form 태그 : 사용자로부터 값을 입력받아 제출 이벤트(Submit Event)가 발생되면
	웹프로그램을 요청하여 입력값을 전달하는 태그</p>
	<p>form 태그의 하위태그로 사용자로부터 값을 입력받기 위한 입력태그와 제출 이벤트(Submit Event)를
	발생하는 태그가 반드시 작성되어 있어야 정상적인 동작 가능</p>
	<p>form 태그는 자바스크립트를 이용하여 사용자 입력값을 검증한 후 정상적인 경우에만 동작되도록
	설정하고 비정상적인 입력값이 있는 경우 form 태그가 동작되지 않도록 설정하는 것을 권장</p>
	<hr>
	<form action="47_form_action.html" method="post" name="loginForm">
	<table>
		<tr>
			<td>아이디</td>
			<!-- 사용자로부터 값을 입력받기 위한 태그 -->
			<td><input type="text" name="id"></td>
		</tr>
		<tr>
			<td>비밀번호</td>
			<td><input type="password" name="passwd"></td>
		</tr>
		<tr>
			<!-- 제출 이벤트(Submit Event)를 발생하는 button 태그 -->
			<!-- => click 이벤트에 의해 제출 이벤트(Submit Event)가 발생되어 form 태그 동작 -->
			<!-- <td colspan="2"><button type="submit">로그인</button></td> -->
			
			<!-- 아무런 이벤트도 발생되지 않는 button 태그 -->
			<td colspan="2"><button type="button" id="loginBtn">로그인</button></td>
		</tr>
	</table>		
	</form>
	
	<script type="text/javascript">
	//form 태그와 입력태그의 name 속성값을 이용하여 Node(Element 객체)로 표현 가능
	//alert(loginForm);//[object HTMLFormElement]
	//alert(loginForm.id);//[object HTMLInputElement]
	
	//InputElement.focus() : 입력태그에 입력촛점을 제공하는 메소드
	loginForm.id.focus();
	
	document.getElementById("loginBtn").onclick=function() {
		//사용자 입력값 검증
		//InputElement.value : 입력태그의 사용자 입력값이 저장된 프로퍼티
		if(loginForm.id.value=="") {//아이디 입력값이 없는 경우
			alert("아이디를 입력해 주세요.");
			loginForm.id.focus();
			return;//이벤트 처리 함수 종료 - form 태그 미실행
		}
	
		//자바스트립트에서는 정규표현식을 / / 안에 작성하면 RegExp 객체로 표현하여 사용 가능
		var idReg=/^[a-zA-Z]\w{5,19}$/g;
		//RegExp.test(input) : RegExp 객체에 저장된 정규표현식으로 매개변수로 전달받은 입력값의 패턴을
		//검사하여 형식에 맞지 않을 경우 [false]를 반환하고 형식에 맞는 경우 [true]를 반환하는 메소드
		if(!idReg.test(loginForm.id.value)) {
			alert("아이디를 형식에 맞게 입력해 주세요.");
			loginForm.id.focus();
			return;
		}
		
		if(loginForm.passwd.value=="") {//비밀번호 입력값이 없는 경우
			alert("비밀번호를 입력해 주세요.");
			loginForm.passwd.focus();
			return;
		}
		
		//form 태그의 속성과 속성값을 자바스크립트로 설정 가능
		//loginForm.action="47_form_action.html";
		//loginForm.method="post";
		
		//FormElement.sumbit() : form 태그를 실행하기 위한 제출 이벤트를 발생하는 메소드
		loginForm.submit();
	}
	</script>
</body>
</html>

 


 


아이디&비밀번호 적은후, [로그인] 클릭시

 


 

48_submit_action

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
	<h1>form 태그 관련 이벤트 - 처리페이지</h1>
	<hr>
</body>
</html>

 

& *** 48_subimt_form

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
	<h1>form 태그 관련 이벤트 - 입력페이지</h1>
	<hr>
	<form action="48_submit_action.html" method="post" name="loginForm">
	<table>
		<tr>
			<td>아이디</td>
			<td><input type="text" name="id"></td>
		</tr>
		<tr>
			<td>비밀번호</td>
			<td><input type="password" name="passwd"></td>
		</tr>
		<tr>
			<td colspan="2"><button type="submit">로그인</button></td>
		</tr>
	</table>		
	</form>
	<hr>
	<!-- 
	<a href="https://www.daum.net" onclick="event.preventDefault();">다음(Daum)으로 이동</a>
	<a href="https://www.daum.net" onclick="return false;">다음(Daum)으로 이동</a>
	-->
	 
	<script type="text/javascript">
	loginForm.id.focus();

	//form 태그에서 제출 이벤트가 발생될 경우 호출될 이벤트 처리 함수 등록
	// => 비정상적인 입력값이 있는 경우 제출 이벤트 취소 - form 태그 미실행
	loginForm.onsubmit=function() {
		if(loginForm.id.value=="") {
			alert("아이디를 입력해 주세요.");
			loginForm.id.focus();
			//태그에서 발생되는 이벤트에 대한 기본 명령을 삭제
			// => form 태그를 이용하여 웹프로그램을 요청하는 명령 취소 - form 태그 미실행
			//event.preventDefault(); 
			//return;
			
			//이벤트 처리 함수에서 return 명령으로 [false]를 반환하면 이벤트 처리 함수를 
			//종료하면서 태그의 기본 명령 제거 및 이벤트 전달 중지
			return false; // form 태그 미실행. // 이벤트가 발생하더라도, form태그가 실행안됨
		}
	
		var idReg=/^[a-zA-Z]\w{5,19}$/g;
		if(!idReg.test(loginForm.id.value)) {
			alert("아이디를 형식에 맞게 입력해 주세요.");
			loginForm.id.focus();
			return false;
		}
		
		if(loginForm.passwd.value=="") {
			alert("비밀번호를 입력해 주세요.");
			loginForm.passwd.focus();
			return false;
		}
	}
	</script>
</body>
</html>

 


49_exception

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
	<h1>자바스크립트 예외처리</h1>
	<hr>
	<p>예외(Exception) : 프로그램 실행시 발생되는 문제(오류)</p>
	
	<script type="text/javascript">
	try {//예외가 발생될 수 있는 명령을 작성하는 영역
		//var array=new Array(100);
		var array=new Array(100000000000);
	
		alert("Array 객체의 요소 갯수 = "+array.length);
	} catch (e) {//try에서 예외가 발생될 경우 예외를 전달받아 실행될 명령을 작성하는 영역
		//alert("프로그램 실행에 문제가 발생하여 종료합니다.");
		alert("예외 메세지 = "+e);
	} finally {
		alert("예외 발생과 상관없이 무조건 실행될 명령입니다.");
	}
	</script>
</body>
</html>

 


 

 


*** 50_cookie

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
	<h1>쿠키(Cookie)</h1>
	<hr>
	<p>쿠키 : 서버와 클라이언트의 연결 지속성을 제공하기 위해 클라이언트에 저장되는 문자값</p>
	<p>클라이언트에 접속된 웹서버의 이름을 식별자로 사용하여 다수의 쿠키를 클라이언트에
	저장해 웹서버의	웹프로그램 요청시 쿠키에 저장된 값을 전달</p>
	<hr>
	<form name="cookieForm">
		아이디 : <input type="text" name="id">&nbsp;&nbsp;
		<button type="button" id="saveBtn">입력 아이디 저장</button>&nbsp;&nbsp;
		<button type="button" id="useBtn">저장 아이디 사용</button>&nbsp;&nbsp;
		<button type="button" id="removeBtn">저장 아이디 삭제</button>&nbsp;&nbsp;
	</form>
	
	<script type="text/javascript">
	//클라이언트에 쿠키를 저장(변경)하는 함수
	// > 쿠키에는 필요한 정보를 이름과 값으로 묶어서 저장(이름=값)
	// > 쿠키에 필요한 정보를 ;를 이용해 구분하여 쿠키에 여러개 저장 가능
	// > 쿠키의 필수 정보로 쿠키명과 쿠키값을 묶어 저장
	// > 쿠키의 선택 정보로 적용범위, 도메인, 지속시간 등을 저장 - 선택 정보를 저장하지 않을 경우 기본값 사용
	function setCookie(name, value, path, expires) {
		var sc=""; // 쿠키를 저장하기 위한 변수
		
		//쿠키변수에 쿠키명과 쿠키값을 묶어서 저장
		// > 쿠키값은 영문자, 숫자, 일부 특수문자만 저장 가능
		// > 영문자, 숫자, 일부 특수문자를 제외한 문자는 부호화 처리하여 저장
		sc+=name+"="+encodeURIComponent(value)+";";
		
		//쿠키변수에 path 이름으로 쿠키의 적용범위를 묶어서 저장
		sc+="path="+path+";";
		
		//클라이언트의 현재 날짜와 시간이 저장된 Date 객체 생성
		var date=new Date();
		//Date.setDate(number) : Date 객체에 저장된 날짜와 시간 중 일을 변경하는 변경하는 메소드
		date.setDate(date.getDate()+expires);
		
		//쿠키변수에 expires 이름으로 쿠키의 지속시간을 묶어서 저장
		//date.toUTCString() : Date 객체에 저장된 날짜와 시간을 세계표준시(UTC)의 문자값을 변환하여 반환하는 메소드
		sc+="expires="+date.toUTCString()+";";
	
		//document.cookie : 쿠키를 저장하기 위한 객체
		document.cookie=sc;//클라이언트에 쿠키 저장
	}
	
	//클라이언트에 저장된 쿠키의 쿠키값을 반환하는 함수
	// > 클라이언트에 저장된 쿠키 중 매개변수로 전달받아 이름의 쿠키값 반환
	function getCookie(name) {
		//쿠키에 저장된 정보를 ; 문자값으로 분리하여 변수에 저장
		var gc=document.cookie.split(";");//변수에 Array 객체 저장
		
		for(i=0;i<gc.length;i++) {
			//Array 객체의 요소값(쿠키정보)을 = 문자값으로 분리하여 첫번째 요소값(이름)을 매개변수로 전달받은 값(쿠키명)과 비교하여 같은 경우
			if(gc[i].split("=")[0] == name) {
				//두번째 요소값(쿠키값)을 반환
				return gc[i].split("=")[1];
			}
		}
		
		//매개변수로 전달받은 이름의 쿠키값이 없는 경우 null 반환
		return null;
	}
	
	//[입력 아이디 저장] 버튼을 클릭한 경우 호출되는 이벤트 처리 함수 등록
	// > 입력태그의 입력값(아이디)를 반환받아 클라이언트의 쿠키로 저장
	document.getElementById("saveBtn").onclick=function() {
		var id=cookieForm.id.value;//입력태그의 입력값을 변수에 저장
		
		if(id=="") {//입력값이 없는 경우
			alert("아이디를 입력해 주세요.");
			return;
		}
		
		// ***(중요!!!) 입력값을 클리이언트의 쿠키값으로 하루동안 저장 
		setCookie("id", id, "/", 1); // id란 이름으로  id 저장. 
		
		// 입력태그의 입력값 초기화
		cookieForm.id.value="";
	}
	
	
	//[저장 아이디 사용] 버튼을 클릭한 경우 호출되는 이벤트 처리 함수 등록
	// > 클라이언트에 저장된 쿠키값을 반환받아 입력태그의 입력값으로 출력
	document.getElementById("useBtn").onclick=function() {
		var id=getCookie("id");
		
		if(id==null) {
			alert("쿠키에 저장된 아이디가 없습니다.");
			return;
		}
		
		//입력태그의 입력값으로 변수값 저장 - 입력값 변경
		cookieForm.id.value=id;
	}
	
	//[저장 아이디 삭제] 버튼을 클릭한 경우 호출되는 이벤트 처리 함수 등록
	// > 클라이언트에 저장된 쿠키 삭제
	document.getElementById("removeBtn").onclick=function() {
		//쿠키의 지속기간을 과거로 변경 - 쿠키 삭제		
		setCookie("id", "", "/", -1);
	}	
	</script>	
</body>
</html>

 


 

아이디 를 적은뒤, [입력 아이디 저장] 클릭

 

[저장 아이디 사용]클릭하면, 저장된 아이디 나옴

 

 

[저장 아이디 삭제] 클릭후, [저장 아이디 사용] 클릭하면, 이벤트창 뜸.