관리 메뉴

프로그래밍

[Web] day34 : 자바스크립트 이벤트 연결01 본문

Web/Web

[Web] day34 : 자바스크립트 이벤트 연결01

시케 2023. 7. 4. 17:26
728x90
반응형

2023.06.22.목

이벤트 연결

웹에서 어떠한 행동을 할 때 변경사항 혹은 어떠한 일을 수행하고 싶을 수 있는데

이러한 '이벤트'를 문서의 요소와 연결 시킬 수있다

 

이벤트 연결상단 배치
무명함수하단 배치가 일반적이다

 

자바스크립트 무명함수 이용

문서의 어떠한 요소를 선택(클릭)하면 함수를 작동시키는 방식이다

클릭해서 이미지 바꾸기 클릭하면 바뀌는 이미지
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>클릭해서 이미지 바꾸기</title>

<style type="text/css">
	#test {
		cursor: pointer;
	}
	
</style>

</head>
<body>

	<img id='test' alt ="클릭하면 바뀌는 이미지" src="test2.jpg">
	
	<!-- 문서의 어떠한 요소를 선택(클릭)하면 함수를 작동시킬거야 -->
	<!-- 무명 함수 -->
	<script type="text/javascript">
		document.querySelector('#test').onclick=function(){
			this.src='test3.png';
		};
	</script>

</body>
</html>

자바스크립트 함수 이용

Insert title here
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<style type="text/css">
	#box {
		width: 100px;
		height: 100px;
		background-color: coral;
		cursor: pointer
	}
	
</style>

<script type="text/javascript">
	// 누른 요소의 스타일 속성 중 배경색을 녹색을 바꿔줘
	function changeColor(obj){
		obj.style.backgroundColor = 'green';
	}
</script>

</head>
<body>

<!-- 이벤트 연결 방식 -->
<div id="box" onClick ="changeColor(this)"></div>

</body>
</html>

 

이벤트 연결 활용

입력받은 문자열 구분

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>입력받은 문자열 구분</title>
</head>
<body>

<h1 id ='header'></h1>

	<script type="text/javascript">
		// 일반적인 방식
		function printInfo(str){
			if (str == 'admin') {
				document.querySelector('#header').append('관리자 페이지입니다.')
			} else {
				document.querySelector('#header').append('환영합니다. ' + str + '님')
			}
		}
		
		function printInfo2(str) {
			if (str == 'admin') {
				document.write('관리자 페이지입니다.')
			} else {
				document.write('환영합니다. ' + str + '님')
			}
		}
		

		var input = prompt('아이디를 입력해주세요.')	
		printInfo(input);
		
	</script>
</body>
</html>

 

728x90
반응형
Comments