JavaScript - event propagation

yeong ·2022년 11월 22일

js

목록 보기
45/49

이벤트(Event) - 이벤트 전달(Event Propagation)
이벤트 전달 : 태그에서 발생된 이벤트가 다른 태그로 전달 - 캡쳐링 >> 타겟 >> 버블링
캡쳐링(Capturing) 단계 : 이벤트가 부모 태그에서 자식 태그로 전달
타겟(Target) 단계 : 이벤트가 발생된 태그로 전달
버블링(Bubbling) 단계 : 이벤트가 자식 태그에서 부모 태그로 전달

<div id="one">
		<div id="two">
			<div id="three"></div>
		</div>
	</div>
<script type="text/javascript">
	document.getElementById("one").onclick=function() {
		location.href="https://www.daum.net";
		//event.stopPropagation() : 이벤트 전달을 중지하는 메소드
  
		event.stopPropagation();
	}
//가장 상위부모이므로 id가 two,three인 버튼 클릭시 캡쳐링에 따라서 부모이벤트가 발생
//event객체.stopPropagation(); :버블링을 막아주는 역할 즉, 하위 요소에서 상위 요소로 이벤트가 전파되는 것을 막아주는 함수 자식에게 고유한 이벤트만 부여하고 싶을 때 사용
document.getElementById("two").onclick=function() {
		location.href="https://www.naver.com";
		event.stopPropagation();
	}
	document.getElementById("three").onclick=function() {
		location.href="https://www.google.com";
		event.stopPropagation();
      //
	}

0개의 댓글