- preventDefault( ) : 기본 이벤트를 제거한다
- stopPropagation( ) : 이벤트 전달을 제거한다
<body>
<h1>
<a href="https://www.naver.com/">네이버</a>
</h1>
</body>
a 태그와 h1 태그에 이벤트를 연결한다 하지만 a 태그의 기본 이벤트가 실행되어서 h1 태그의 이벤트가 소용이 없는 상황이 된다
$(function () {
$('a').click(function (event) {
$(this).css('background-color', 'blue');
event.preventDefault();
});
$('h1').click(function () {
$(this).css('background-color', 'red');
});
});
코드를 실행하면 a 태그 클릭시 a 태그 이외에 h1 태그에도 이벤트 전달이 일어난다
이벤트 전달을 막으려면 이벤트 객체의 stopPropagation( ) 메서드를 사용한다
$(function () {
$('a').click(function (event) {
$(this).css('background-color', 'blue');
event.stopPropagation();
event.preventDefault();
});
$('h1').click(function () {
$(this).css('background-color', 'red');
});
});
a 태그를 클릭해도 이벤트 전달이 일어나지 않는다
stopPropagation( ) 메서드와 preventDefault( ) 메서드를 함께 사용하는 경우가 많으므로
jQuery에서는 간단하게 return false를 사용해서 두 가지를 함께 적용하는 것으로 인식한다
$(function () {
$('a').click(function (event) {
$(this).css('background-color', 'blue');
return false;
});
$('h1').click(function () {
$(this).css('background-color', 'red');
});
});
기존 자바스크립트는 return false를 사용하면 기본 이벤트만 제거된다는 점을 주의
'Frontend > jQuery' 카테고리의 다른 글
| JS jQuery (part. 28) - 마우스 이벤트 (0) | 2020.08.11 |
|---|---|
| JS jQuery (part. 27) - 이벤트 연결 범위 한정 (0) | 2020.08.11 |
| JS jQuery (part. 25) - 이벤트 강제 발생 (0) | 2020.08.10 |
| JS jQuery (part. 24) - 이벤트 객체 활용 (0) | 2020.08.10 |
| JS jQuery (part. 23) - 매개변수 context (0) | 2020.08.10 |