<h1 id="header">
<p id="paragraph">Paragraph</p>
</h1>
window.onload = function () {
document.getElementById('header').onclick = function () {
alert('header');
};
document.getElementById('paragraph').onclick = function () {
alert('paragraph');
};
};
p 태그를 클릭하면 이벤트 버블링이 일어나면서 paragraph => header 순으로 경고창이 출력됨
여기서 이벤트의 전달을 막아보자
인터넷 익스플로러와 그외 브라우저가 이벤트 전달을 막는 방법이 다름
- 인터넷 익스플로러 : 이벤트 객체의 cancelBubble 속성을 true로 변경
- 그 이외의 브라우저 : 이벤트 객체의 stopPropagation() 메서드 사용
window.onload = function () {
document.getElementById('header').onclick = function () {
alert('header');
};
document.getElementById('paragraph').onclick = e => {
var event = e || window.event;
alert('paragraph');
// 인터넷 익스플로러
event.cancelBubble = true;
// 그 이외의 브라우저
if (event.stopPropagation) {
event.stopPropagation();
}
};
};
'Frontend > Java Script' 카테고리의 다른 글
| JS event (part. 08) - 표준 이벤트 모델 (0) | 2020.07.28 |
|---|---|
| JS event (part. 07) - 인터넷 익스플로러 이벤트 모델 (0) | 2020.07.27 |
| JS event (part. 05) - 디폴트 이벤트 제거 (0) | 2020.07.27 |
| JS event (part. 04) - 이벤트 강제 실행 (0) | 2020.07.27 |
| JS event (part. 03) - 이벤트 발생 객체와 이벤트 객체 (0) | 2020.07.25 |