고래씌

[jQuery] 12. 이벤트(on메소드, 키보드 관련 메소드) 본문

Front-End/jQuery

[jQuery] 12. 이벤트(on메소드, 키보드 관련 메소드)

고래씌 2023. 11. 15. 21:06

1. 이벤트 핸들러 연결 방법 종류

1) 방법1. 이벤트 메소드를 통한 연결

        $("선택자").이벤트메소드(function(){
            // 실행내용
        })

 

    <h4 id="test1">클릭해보시오</h4>

    <script>
        $(function(){
            $("#test1").click(function(){
                $(this).html("클릭되었습니다.");
            })

            $("#test1").dblclick(function(){   // 더블클릭
                $(this).css("color", "red");
            })
        })
    </script>

 

 

 

 

2) 방법2. on 메소드를 이용한 방법

▶ on메소드는 이벤트 연결시 하나의 요소에 다중으로 이벤트 부여가 가능하다.

ex)

    $("#test2").on("click",function(){
         $(this).css('background','orangered').text('클릭됨')
    })

 

    <h4 id="test2">마우스 클릭 및 올려보세요.</h4>

    <script>
        $(function(){

            $("#test2").on({
            "click": function(){
                // 기존에 부여된 이벤트 제거(mouseenter, mouseout)
                $(this)
                .off("mouseenter")  // 제거
                .off("mouseout")     // 제거
                .css('background', 'orangered')   // 이 색깔 모두
                .text("이벤트 제거");   // text 표시 
            },
            "mouseenter": function(){
                $(this).css('background', 'yellow').text('마우스 올라감');
            },
            "mouseout": function(){
                $(this).css('background','yellowgreen').text("마우스 빠져나감");
            }
            },
            )
        })
    </script>

 

 

 

 

3) 방법3

$("상위요소선택자").on("이벤트명","하위요소선택자",function(){
    선택된 상위요소안에 존재하는 하위요소에 이벤트 발생시 실행할 내용을 정의
})

 

    <div id="wrap">
        <h4>h4 클릭해보시오.</h4>
        <h5>h5 클릭해보시오.</h5>
    </div>

    <script>
        $(function(){
            $("#wrap>h4").on("click",function(){
                $(this).css("color","red");
            });

            $("#wrap").on("click","h4",function(){
                $(this).html("안녕");
            });

            $(document).on("click","h4,h5", function(){
                // 이 문서상의 요소들중 모든 h4,h5에 대해 이벤트 발생 시
                $(this).css('color','pink');
            })
        })
    </script>

 

 

 

4) 동적으로 만들어진 요소에도 동일한 이벤트를 적용시키고자 한다면?

=> 반드시 3번 방법으로 이벤트 추가

 

 

동적으로 만들어진 요소 ?
    처음 문서 로딩시점에는 없다가, 나중에 js, jquery 등을 통해 새롭게 만들어지는 요소

 

    <div id="wrap2" style="border:1px solid red;">
        <h6>기존에 존재하는 요소</h6>
    </div>

 

▶ 방법 ①

    <script>
        $(function(){
            // 방법 1.
            $("#wrap2>h6").click(function(){
                const copy = $(this).clone(true).text("클릭으로 인해 동적으로 생성된 요소");
                // $("#wrap2").append("<h6>클릭으로 인해 동적으로 생성된 요소</h6>")

                $("#wrap2").append(copy);  // => 모든 이벤트 적용돼서 복사본도 이벤트 사용가능
            })
        })
    </script>

 

 

▶ 방법 ②

    <script>
        $(function(){
            // 방법 2.
            $("#wrap2>h6").on("click",function(){
                $(this).clone(true).text("클릭으로 인해 동적으로 생성된 요소").appendTo("#wrap2");
                // $("wrap2").append("<h6>클릭으로 인해 동적으로 생성된 요소</h6>");   // 실행안됨

            })
        })
    </script>

 

 

▶ 방법 ③. 동적으로 만들어진 요소에 이벤트를 적용시키는 방법

    <script>
        $(function(){
            // 방법 3.
            $("#wrap2").on("click","h6",function(){
                $("#wrap2").append("<h6>클릭으로 인해 동적으로 생성된 요소</h6>")
            })
        })
    </script>

 

 

 


2. 키보드 관련 이벤트

- keydown / keypress : 키가 눌려질 때 발생하는 이벤트
  keydown : 키보드의 모든 키가 눌려질 때 발생 
  keypress : 키보드의 펑션키, 기능키, 한글제외한 나머지키가 눌려질 때 발생

 

- keyup : 키가 떼어질 때 발생

 

    <div>
        150자 내로 작성하시오 <br>
        <textarea name="" id="content" cols="30" rows="10" maxlength="150"></textarea>
        <br>
        <span id="count">0</span>  / 150
    </div>

    <input type="text" id="test4">

    <script>
        $(function(){
            $("#content").keyup(function(){
                const textLength = $(this).val().length;
                $("#count").text(textLength);
            })

            $("#test4").keyup(function(){
                console.log($(this).val());
            })
        })
    </script>