본문 바로가기
WEB/JavaScript

이벤트 : 기본 이벤트 취소

by 노랑파랑 2016. 10. 17.
반응형




기본 이벤트 

* 웹 브라우저의 기본 요소들의 기본 동작

* 예 ) a 태그를 클릭하면 href 속성의 URL로 이동한다.

  예 ) 폼에서 submit을 누르면 데이터가 전송된다. 

  예 ) 텍스트 필드에 포커스를 맞춘 상태에서 키보드로 켁스트를 입력할 수 있다.



1. inline

* 이벤트의 리턴 값이 false 이면 이벤트가 취소된다.

 - 예제                            >실행 화면 링크<

<p> <label>prevent event on</label> <input id="prevent" type="checkbox" name="eventprevent" value="on" checked/>    // 체크를 하면 이벤트 취소 </p> // 태그 이벤트 막기 <p> <a href="http://bravesuccess.tistory.com/" onclick="if(document.getElementById('prevent').checked) return false;">My Blog</a> </p> // submit 이벤트 막기 <p> <form action="http://bravesuccess.tistory.com/" onsubmit="if(document.getElementById('prevent').checked) return false;"> <input type="submit" /> </form> </p>




2. Property 방식

* 리턴 값이 false면 이벤트 취소

-예제                            >실행 화면 링크<

<p> <label>prevent event on</label> <input id="prevent" type="checkbox" name="eventprevent" value="on" checked /> </p> <p> <a href="http://bravesuccess.tistory.com/" >My Blog</a> </p> <p> <form action="http://bravesuccess.tistory.com/" > <input type="submit" /> </form> </p> <script> document.querySelector('a').onclick = function(event){        // <a> 태그 이벤트 막기 if(document.getElementById('prevent').checked) return false; }; document.querySelector('form').onclick = function(event){    // submit 이벤트 막기 if(document.getElementById('prevent').checked) return false; }; </script>





3. addEventListener() 방식

* 이벤트 객체의 preventDefault 메소드를 실행하면 기본 이벤트가 취소된다.

* IE9 이하 버전에서는 event.returnValue의 값을 false로 해준다.

- 예제                         >실행 화면 링크<

<p> <label>prevent event on</label> <input id="prevent" type="checkbox" name="eventprevent" value="on" checked /> </p> <p> <a href="http://bravesuccess.tistory.com/" >My Blog</a> </p> <p> <form action="http://bravesuccess.tistory.com/" > <input type="submit" /> </form> </p> <script> document.querySelector('a').addEventListener('click', function(event){ if(document.getElementById('prevent').checked) event.preventDefault();        // <a> 태그 이벤트 막기 }); document.querySelector('form').addEventListener('submit', function(event){ if(document.getElementById('prevent').checked) event.preventDefault();        //submit 이벤트 막기 }); </script>

반응형

'WEB > JavaScript' 카테고리의 다른 글

네트워크 : Ajax  (0) 2016.10.19
이벤트 : Type  (0) 2016.10.17
이벤트 : 전파  (0) 2016.10.16
이벤트 : 등록방법  (0) 2016.10.16
이벤트  (0) 2016.10.16