쌍용교육센터 - 38일

개발자가 되고 싶어요 ㅣ 2024. 4. 11. 19:25

2024.04.11

기본 이벤트

<script type="text/javascript">
	window.onload=function(){
		const alink = document.getElementById('alink');
		//이벤트 연결
		alink.onclick=function(){
			alert('이벤트 연결');
			//기본 이벤트 제거
			return false;
		};
		
		const myForm = document.getElementById('myForm');
		//이벤트 연결
		myForm.onsubmit=function(){
			const name = document.getElementById('name');
			alert(name.value);
			//기본 이벤트 제거
			return false;
		};
	};
</script>

 

이벤트 전달

<script type="text/javascript">
/*
이벤트 전파(전달) : 특정 태그에서 이벤트가 발생하면 다른 태그로 이벤트가 전달되는 현상

이벤트 버블링 : 자식 노드에서 부모 노드 순으로 이벤트를 실행하는 것을 의미
    div
     |         ^
    div        | 
     |         |    부모 태그로 이벤트 전파
     p         |
     |  
    span       <--- 이벤트 발생 

이벤트 캡쳐링 : 부모 노드에서 자식 노드 순으로 이벤트를 실행하는 것을 의미
 */
	window.onload=function(){
		//이벤트 연결
		document.getElementById('space').onclick=function(){
			alert('space');
			this.style.background='pink';
		};
		document.getElementById('paragraph').onclick=function(event){
			alert('paragraph');
			this.style.background='yellow';
			
			//이벤트 전달 제거
			event.stopPropagation();		
		};
	};
</script>

 

표준 이벤트 모델

<script type="text/javascript">
/*
DOM Level 2 표준 이벤트 모델
addEventListener(eventType,eventHandler,useCapture) : 이벤트 연결
removeEventListener(eventType,eventHandler) : 이벤트 제거
 */
	//윈도우가 로드될 때 매개변수로 전달된 함수를 실행
	window.addEventListener('load',function(){
		const header = document.getElementById('header');
		//이벤트 연결
		header.addEventListener('click',function(){
			alert('이벤트 연결');
		},false);
	},false);
</script>

 

예외처리

<script type="text/javascript">
	//예외가 발생하지 않는 경우
	document.write('1<br>');
	try{
		//예외가 발생할 가능성이 있는 문구
		document.write('2<br>');
	}catch(exception){
		document.write('3<br>');
	}
	document.write('4<br>');
	document.write('----------------<br>');
	//예외가 발생한 경우
	document.write('1<br>');
	try{
		document.write(num);//예외 발생
		document.write('2<br>');
	}catch(Exception){
		document.write('3<br>');
	}
	document.write('4');
</script>

 

예외 발생 및 finally

<script type="text/javascript">
	try{
		let result = 10/0;
		
		if(!isFinite(result)){//수를 0으로 나눌 때
			//예외를 일부러 발생시킴
			throw 'DivideByZeroException';
		}
		
	}catch(exception){
		document.write(exception);
	}finally{
		document.write('<br>오류가 있거나 또는 없어도 반드시 수행');
	}
	document.write('<br>프로그램 끝!!');
</script>

'IT 국비 교육' 카테고리의 다른 글

쌍용교육센터 - 40일  (0) 2024.04.15
쌍용교육센터 - 39일  (0) 2024.04.12
쌍용교육센터 - 37일  (0) 2024.04.09
쌍용교육센터 - 36일  (0) 2024.04.08
쌍용교육센터 - 35일  (0) 2024.04.05