부모 자식 노드 관계에서 만약 이름이 같은 이벤트가 각각 있다면 ( 아래와 같이 )



<div onclick="test1('1번 div')" class="div-test div1">

<div onclick="test1('2번 div')" class="div-test div2">

<div onclick="test1('3번 div')" class="div-test div3">

<div onclick="test1('4번 div')" class="div-test div4">

</div>

</div>

</div>

</div>


이와 같이 되어있다면 제일 바깥의 div를 클릭하면 이벤트가 한번 일어나지만


제일 안쪽의 div를 누르면 4번 3번 2번 1번 순으로 전부 실행되어 버린다


이와 같은 현상을 버블링이라고 하고


이를 방지하는 방법을 알아보자.


stopPropagation, cancelBubble 키워드를 사용하고 상위 이벤트 작동을 차단한다.



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
	.div-test {
		border:1px solid black;
		padding:20px;
	}
	.div1 {background:red;}
	.div2 {background:orange;}
	.div3 {background:yellow;}
	.div4 {background:green;}
</style>
</head>
<body>
	<h1>이벤트 전달</h1>
	<h3>이벤트 버블링</h3>
	<p>자식 노드에서 부모 노드로 이벤트가 전달된다.</p>
	<div onclick="test1('1번 div')" class="div-test div1">
		<div onclick="test1('2번 div')" class="div-test div2">
			<div onclick="test1('3번 div')" class="div-test div3">
				<div onclick="test1('4번 div')" class="div-test div4">
				</div>
			</div>
		</div>
	</div>
	
	<script type="text/javascript">
		function test1(msg) {
			alert(msg);
		}
		// 자식의 노드를 클릭하면 부모 노드의 이벤트도 전부 실행된다.
	</script>
	
	<hr>
	
	<h3>이벤트 버블링 막기</h3>
	
	<div onclick="test2('1번 div')" class="div-test div1">
		<div onclick="test2('2번 div')" class="div-test div2">
			<div onclick="test2('3번 div')" class="div-test div3">
				<div onclick="test2('4번 div')" class="div-test div4">
				</div>
			</div>
		</div>
	</div>
	<script type="text/javascript">
		function test2(msg, e) {
			var event = e || window.event;
			
			alert(msg);
			
			// IE 제외
			if(event.stopPropagation()){
				event.stopPropagation();
			}
			
			// IE 전용
			event.cancelBubble = true;
		}
	</script>
	
</body>
</html>


+ Recent posts