preventDefault()와 stopPropagation()
preventDefault()
HTML에서 a
태그나 submit
은 고유 동작이 있다. 페이지를 이동시키거나 form
안에 있는 input
등을 전송하는 동작을 preventDefault()를 통해 중단할 수 있다.
<a href="https://velog.io/@solda">솔로그</a>
$("a").click(e=>{ e.preventDefault() });
a
태그의href
속성이 중단된다.form
태그가 없으면button
의onClick
이벤트에서 전송을 중단할 필요 없다.
stopPropagation()
<div class="first">
<ul class="second">
<li class="third">
Hello
</li>
</ul>
</div>
$(".third").click(function(e){
e.stopPropagation();
alert("third");
});
$(".second").click(function(){
alert("second");
});
$(".first").click(function(){
alert("first");
});
- Hello를 클릭하면 부모 element까지 propagation되어
third > second > first
순으로 경고를 띄우지만e.stopPropagation()
를 통해 이벤트를 중단시킬 수 있다. alert()
메서드보다 윗 줄에 적어도 해당 함수는 수행하는 것을 염두에 둔다.
결론
preventDefault()
는 고유 동작을 중단시키고, stopPropagation()
은 상위 태그로의 전파를 중단시킨다.
Author And Source
이 문제에 관하여(preventDefault()와 stopPropagation()), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@solda/preventDefault와-stopPropagation저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)