코밍이의 하루

[JQuery] 그룹 이벤트 등록 및 삭제하기 본문

웹언어 공부/JQuery

[JQuery] 그룹 이벤트 등록 및 삭제하기

코밍이 2021. 8. 20. 01:12

1. 개발 환경

구분 내용
사용 언어 HTML5, CSS3, JS, jQuery
개발환경 Visual Studio Code
참고 도서 [Do it] 자바스크립트 + 제이쿼리 입문
웹브라우저 Chrome

2. 주요 문법

1) 그룹 이벤트 등록 메소드

- 한 번에 2개 이상의 이벤트를 등록할 수 있음.

- 그룹 이벤트 등록 메소드 종류

종류 설명
on() - 이벤트 대상 요소에 2개 이상의 이벤트 등록
- 사용 방식에 따라 이벤트를 등록한 이후에도 동적으로 생성되거나 복제된 요소에도 이벤트 적용
bind() 이벤트 대상 요소에 2개 이상의 이벤트 등록
delegate() - 선택한 요소의 하위 요소에 이벤트 등록
- 이벤트를 등록한 이후에도 동적으로 생성되거나 복제된 요소에도 이벤트 적용
one() - 이벤트 대상 요소에 1개 이상의 이벤트 등록
- 지정한 이벤트가 1회 발생하고 자동으로 해제

2) 이벤트 제거 메소드

- 이전 등록된 이벤트 제거

종류 설명
off() on() 메소드로 등록한 이벤트 제거
unbind() bind() 메소드로 등록한 이벤트 제거
undelegte() delegate() 메소드로 등록한 이벤트 제거

 

3. 소스 코드 및 실행 결과

- jq_event2_6_test.html

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title> 이벤트 </title>  
		<script src="js/jquery.js"></script>
		<script>
			$(function(){
				$(".btn_1.on").on("mouseover focus", function(){
					alert("HELLO!");
				});
				$(".btn_1").addClass("on");

				$(document).on("mouseover focus", ".btn_2.on", function(){
					alert("WELCOME!");
				});
				$(".btn_2").addClass("on");
			});			
		</script>
		</head>
	<body>
		<div id="wrap">
			<p><button class="btn_1">버튼1</button></p>
			<p><button class="btn_2">버튼2</button></p>
		</div>
	</body>
</html>

jq_event2_6_test.html

- jq_event2_7_test.html

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title> 이벤트 </title>  
		<script src="js/jquery.js"></script>
		<script>
			$(function(){
				$(".btn_wrap").delegate(".btn_1.on", "mouseover focus", function(){
					alert("HELLO!");
				});
				$(".btn_1").addClass("on");

				$(document).one("mouseover focus", ".btn_2.on", function(){
					alert("WELCOME!");
				});
				$(".btn_2").addClass("on");
			});
		</script>
	</head>
	<body>
	<div id="wrap">
		<p class="btn_wrap">
			<button class="btn_1">버튼1</button>
		</p>
		<p><button class="btn_2">버튼2</button></p>
	</div>
	</body>
</html>

jq_event2_7_test.html

- jq_event2_8_test.html

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title> 이벤트 </title>  
		<script src="js/jquery.js"></script>
		<script>
			$(function(){
				$(".btn_1").on("mouseover", function(){
					alert("HELLO!");
				});
				$(document).on("mouseover", ".btn_2", function(){
					alert("WELCOME!");
				});
				var btn_2 = $("<p><button class=\"btn_2\">버튼2</button></p>");
				$("#wrap").append(btn_2);

				$(".del_1").on("click", function(){
					$(".btn_1").off("mouseover");
				});
				$(".del_2").on("click", function(){
					$(document).off("mouseover", ".btn_2");
				});
			});
		</script>
	</head>
	<body>
	<div id="wrap">
		<p><button class="btn_1">버튼1</button></p>
	</div>
	<p>
		<button class="del_1">버튼1 이벤트 해지</button> 
		<button class="del_2">버튼2 이벤트 해지</button>
	</p>
	</body>
</html>

jq_event2_8_test.html