ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 웹브라우저 자바스크립트 - 기본동작의 취소
    JavaScript/생활코딩 2018. 11. 30. 14:52



    기본동작의 취소 - https://opentutorials.org/course/1375/6769



    웹브라우저의 구성요소들은 각각 기본적인 동작 방법을 가지고 있다.


    - 텍스트 필드에 포커스를 준 상태에서 키보드를 입력하면 텍스트가 입력된다.

    - 폼에서 submit 버튼을 누르면 데이터가 전송된다.

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


    이러한 기본적인 동작들을 기본 이벤트라고 하는데 사용자가 만든 이벤트를 이용해서 이러한 기본 동작을 취소할 수 있다.




    inline


    inline방식으로 취소하는 방법


    <!DOCTYPE html>

    <html>

    <body>

    <p>

        <label>prevent event on</label><input id="prevent" type="checkbox" name="eventprevent" value="on" />

    </p>

    <p>

        <a href="http://opentutorials.org" onclick="if(document.getElementById('prevent').checked) return false;">opentutorials</a> <!--return값을 false를 해주면 브라우저의 동작을 취소할 수 있다.-->

    </p>

    <p>

        <form action="http://opentutorials.org" onsubmit="if(document.getElementById('prevent').checked) return false;">

                <input type="submit" />

        </form>

    </p>

    </body>

    </html>










    property 방식


    property방식으로 취소하는 방법


    <p>

        <label>prevent event on</label><input id="prevent" type="checkbox" name="eventprevent" value="on" />

    </p>

    <p>

        <a href="http://opentutorials.org">opentutorials</a>

    </p>

    <p>

        <form action="http://opentutorials.org">

                <input type="submit" />

        </form>

    </p>

    <script>

        document.querySelector('a').onclick = function(event){

            if(document.getElementById('prevent').checked) //input의 id값이 체크되어 있으면 false를 리턴하여 기본동작을 취소함

                return false;

        };

         

        document.querySelector('form').onclick = function(event){

            if(document.getElementById('prevent').checked)

                return false;

        };

     

    </script>










    addEventListener방식


    addEventListener방식으로 취소하는 방법


    <p>

                <label>prevent event on</label><input id="prevent" type="checkbox" name="eventprevent" value="on" />

            </p>

            <p>

                <a href="http://opentutorials.org">opentutorials</a>

            </p>

            <p>

                <form action="http://opentutorials.org">

                        <input type="submit" />

                </form>

            </p>

            <script>

                document.querySelector('a').addEventListener('click', function(event){

                    if(document.getElementById('prevent').checked)

                        event.preventDefault(); //event가 가지고있는 메소드중 preventDefault()을 가지고 있는데 이것을 사용하면 기본동작이 취소된다.

                });

                 

                document.querySelector('form').addEventListener('submit', function(event){

                    if(document.getElementById('prevent').checked)

                        event.preventDefault();

                });

     

            </script>





    댓글

Designed by Tistory.