preventDefault()와 stopPropagation()

preventDefault()

HTML에서 a 태그나 submit은 고유 동작이 있다. 페이지를 이동시키거나 form안에 있는 input 등을 전송하는 동작을 preventDefault()를 통해 중단할 수 있다.

<a href="https://velog.io/@solda">솔로그</a>

솔로그

$("a").click(e=>{ e.preventDefault() });
  • a태그의 href 속성이 중단된다.
  • form태그가 없으면 buttononClick 이벤트에서 전송을 중단할 필요 없다.

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()은 상위 태그로의 전파를 중단시킨다.

좋은 웹페이지 즐겨찾기