프로그래밍/자바스크립트

자바스크립트 - 이벤트 버블링과 버블링 막는 방법

가카리 2014. 9. 7. 13:15
반응형

이벤트 버블링이란 이벤트가 자식부터 부모까지 계속 실행되는 것을 말한다.


<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>Insert title here</title>

<script>

        window.onload = function(){

        

}

</script>


<style>

        * {border: 3px solid black;}

</style>

</head>

<body>

        <div onclick="alert('outer-div')">

        <div onclick="alert('inner-div')">

        <h1 onclick="alert('header')">

        <p onclick="alert('pagagraph')">Pagagraph</p>

        </h1>

        </div>

        </div>


</body>

</html>


위와 같은 소스의 경우 pagagraph 다음 header 다음 inner-div 다음 outer-div 순으로 실행이 될 것이다.








만약 이벤트 버블링을 막고 싶다면?


다음과 같이


인터넷 익스플로러 : 이벤트 객체의 cancelBubble 속성을 true로 바꿈

그 외 브라우저 : 이벤트 객체의 stopPropagation() 메서드를 사용


으로 막습니다.

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>Insert title here</title>

<script>

        window.onload = function(){

        

        document.getElementById('header').onclick = function(){

        alert('header');

        };

        

        document.getElementById('paragraph').onclick = function(e){

        //이벤트 객체를 처리합니다.

        var event = e || window.event;

        

        //이벤트 발생을 알립니다.

        alert('paragraph');

        

        //이벤트 전달을 제거합니다.

        event.cancelBubble = true;

        if(event.stopPropagation){

        event.stopPropagation();

        }

        }

        

        

        

        }

</script>


</head>

<body>

        <h1 id="header">

        <p id="paragraph">Paragraph</p>

        </h1>

</body>

</html>




이전과 다르게 paragraph만 뜨고 다른 것은 뜨지 않습니다.



반응형