JQuery 정복하기 3 (event, element, form)

    이벤트란?

    • 시스템에서 일어나는 사건을 의미
    • javascript나 jQuery에게 이벤트란 브라우져에서 일어나는 사건을 의미한다. (클릭, 마우스 이동, 타이핑, 페이지 로딩등)
    • 이벤트가 발생했을 때 작동할 로직을 시스템에게 알려두면 이벤트가 발생했을 때 시스템이 그 로직을 호출한다.

    jQuery의 이벤트

    • 크로스브라우징의 문제를 해결해줌
    • bind로 이벤트 핸들러를 설치하고, unbind로 제거 (예제1) (on,off로 업데이트 됨)
    • trigger로 이벤트 핸들러를 강제로 실행 (예제2)
    • click, ready와 같이 다양한 이벤트 헬퍼(helper)를 제공함
    • live를 이용하면 현재 존재 하지 않는 엘리먼트에 이벤트 핸들러를 설치할 수 있음

    예제1. on, off, trigger를 이용한 이벤트의 설치, 제거, 호출

      
    <html>
        <head>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
            <script type="text/javascript">
                function clickHandler(e){
                    alert('thank you');
                }
                //보통 이벤트 함수에 사용되는 기능은 재사용되지 않기 때문에 익명함수를 사용
                $(document).on('ready', function(){ 
                     $('#click_me').on('click', clickHandler);
                     $('#remove_event').on('click', function(e){
                         $('#click_me').off('click', clickHandler);
                     });
                     $('#trigger_event').on('click', function(e){
                         $('#click_me').trigger('click');
                     });
                 })
            </script>
        </head>
        <body>
            <input id="click_me" type="button" value="click me" />
            <input id="remove_event" type="button" value="off" />
            <input id="trigger_event" type="button" value="trigger" />
        </body>
    </html>

    예제2. 이벤트 헬퍼

      
    <html>
        <head>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
            <script type="text/javascript">
                function clickHandler(e){
                    alert('thank you');
                }
                $(document).ready(function(){
                     $('#click_me').click(clickHandler);
                     $('#remove_event').click(function(e){
                         $('#click_me').off('click', clickHandler);
                     });
                     $('#trigger_event').click(function(e){
                         $('#click_me').trigger('click');
                     });
                 })
            </script>
        </head>
        <body>
            <input id="click_me" type="button" value="click me" />
            <input id="remove_event" type="button" value="off" />
            <input id="trigger_event" type="button" value="trigger" />
        </body>
    </html>

    예제3. on를 이용하면 존재하지 않는 엘리먼트에 대해서 이벤트를 설치할 수 있다.

      
    <html>
        <head>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
            <script type="text/javascript">
                function clickHandler(e) {
                    alert('thank you');
                }
                $('#click_me').live('click', clickHandler);
                $('#remove_event').live('click', function(e) {
                    $('#click_me').die('click', clickHandler);
                });
                $('#trigger_event').live('click', function(e) {
                    $('#click_me').trigger('click');
                });
            </script>
        </head>
        <body>
            <input id="click_me" type="button" value="click me" />
        <input id="remove_event" type="button" value="off" />
        <input id="trigger_event" type="button" value="trigger" />
        </body>
    </html>


    엘리먼트 제어

    📍 자식으로 삽입 (.append(), .appendTo(), .html(), .prepend(), .prependTo(), .text())

    
    <!DOCTYPE html>
    <html>
        <head>
            <style>
                p {
                    background:yellow;
                }
            </style>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <p>
                I would like to say:
            </p>
            <script>$("p").append("<strong>Hello</strong>");</script>
        </body>
    </html>

    📍 형제로 삽입 (.after(), .before(), .insertAfter(), .insertBefore())

    
    <!DOCTYPE html>
    <html>
        <head>
            <style>
                p {
                    background:yellow;
                }
            </style>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <p>
                I would like to say:
            </p>
            <script>$("p").after("<b>Hello</b>");</script>
        </body>
    </html>

    📍부모로 감싸기 (.unwrap(), .wrap(), .wrapAll(), .wrapInner())

    
    <!DOCTYPE html>
    <html>
        <head>
            <style>
                div {
                    border:2px blue solid;
                    margin:2px;
                    padding:2px;
                }
                p {
                    background:yellow;
                    margin:2px;
                    padding:2px;
                }
                strong {
                    color:red;
                }
            </style>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <span>Span Text</span>
            <strong>What about me?</strong>
            <span>Another One</span>
            <script>$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");</script>
        </body>
    </html>

    📍삭제 (.detach(), .empty(), .remove(), .unwrap())

    
    <!DOCTYPE html>
    <html>
        <head>
            <style>
                p {
                    background:yellow;
                    margin:6px 0;
                }
            </style>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <p>
                Hello
            </p>
            how are
            <p>
                you?
            </p>
            <button>
                Call remove() on paragraphs
            </button>
            <script>
                $("button").click( function () {
                    $("p").remove();
                });
            </script>
        </body>
    </html>
    

    📍치환 (.replaceAll(), .replaceWith())

    
    <!DOCTYPE html>
    <html>
        <head>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <p> Hello </p>
            <p> cruel </p>
            <p> World </p>
            <script>$("<b>Paragraph. </b>").replaceAll("p"); // check replaceWith() examples        </script>
        </body>
    </html>

    📍클래스 (.addClass(), .hasClass(), .removeClass(), .toggleClass())

    
    <!DOCTYPE html>
    <html>
        <head>
            <style>p {
                    margin: 4px;
                    font-size:16px;
                    font-weight:bolder;
                    cursor:pointer;
                }
                .blue {
                    color:blue;
                }
                .highlight {
                    background:yellow;
                }
            </style>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <p class="blue"> Click to toggle </p>
            <p class="blue highlight"> highlight </p>
            <p class="blue"> on these </p>
            <p class="blue"> paragraphs </p>
            <script>
                 $("p").click( function () {
                     $(this).toggleClass("highlight");
                 });
             </script>
        </body>
    </html>

    📍속성제어 (.attr(), .prop(), .removeAttr(), .removeProp(), .val())

    <!DOCTYPE html>
    <html>
        <head>
            <style>p {
                    color:blue;
                    margin:8px;
                }
            </style>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <input type="text" value="some text"/>
            <p>
            </p>
            <script>$("input").keyup( function () {
                    var value = $(this).val();
                    $("p").text(value);
                }).keyup();</script>
        </body>
    </html>

    폼(form)

    • 서버로 데이터를 전송하기 위한 수단
    • Query는 폼을 제어하는데 필요한 이벤트와 메소드를 제공한다.
    • jQuery 폼 API 문서 : http://api.jquery.com/category/forms/

    📍예제1. (.focus(), .blur(), .change(), .select())

    <!DOCTYPE html>
    <html>
        <head>
            <style>
                span {
                }
            </style>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <p>
                <input type="text" />
                <span></span>
            </p>
            <script>
                $("input").focus( function () {
                    $(this).next("span").html('focus');
                }).blur( function() {
                    $(this).next("span").html('blur');
                }).change(function(e){
                    alert('change!! '+$(e.target).val());
                }).select(function(){
                    $(this).next('span').html('select');
                });
            </script>
        </body>
    </html>
    

    📍예제2. (.submit(), .val())

    <!DOCTYPE html>
    <html>
        <head>
            <style>
                p {
                    margin:0;
                    color:blue;
                }
                div, p {
                    margin-left:10px;
                }
                span {
                    color:red;
                }
            </style>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
            <p>
                Type 'correct' to validate.
            </p>
            <form action="javascript:alert('success!');">
                <div>
                    <input type="text" />
     
                    <input type="submit" />
                </div>
            </form>
            <span></span>
            <script>
                $("form").submit( function() {
                    if ($("input:first").val() == "correct") {
                        $("span").text("Validated...").show();
                        return true;
                    }
                    $("span").text("Not valid!").show().fadeOut(1000);
                    return false;
                });
            </script>
        </body>
    </html>
    반응형

    댓글