카테고리 없음

jQuery이벤트

mi-ni 2024. 2. 1. 08:51

이벤트 핸들러(이벤트 발생시 실행할 function)연결방법 

 

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

$("선택자").이벤트메소드(function(){

      선택자에게 해당 이벤트 메소드 발생했을 때 실행할 내용;

})

<h4 id="test1">클릭해보세요</h4>
     
    <script>
        $(function(){
            $("#test1").click(function(){
                $(this).html("클릭되었습니다.");
            });

            $("#test1").dblclick(function(){
                $(this).css("color","red");
            })

            $("#test1").click(function(){
                $(this).css("backgroundColor","pink"); // 기존에 작성 + 나중에 작성 둘다 실행 
            })
        })
    </script>

 

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

$("선택자").on("이벤트명",function(){

      해당 선택자에 이벤트 발생시 실행할 내용;

});

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

    <script>
        $(function(){
            /*
            $("#test2").on("mouseenter",function(){});
            $("#test2").on("mouseout",function(){});
            */

            // on 메소드를 통해 이벤트 연결시
            // 한 요소에 다중으로 이벤트 걸기 가능 
            $("#test2").on({"mouseenter":function(){
                $(this).css("backgroundColor","yellowgreen").text("마우스 올라감");
            },"mouseout":function(){
                $(this).css("backgroundColor","yellow").text("마우스 빠져나감");
            }, "click" :function(){
                // 기존에 잘 수행됐던 mouseenter, mouseout 이벤트 핸들러 제거
                // * off 메소드 : 이벤트 핸들러 제거 후 해당 요소 반환
                $(this).off("mouseenter").off("mouseout").css("backgroundColor","orange").text("이벤트가 제거됨");
            }});


        })
    </script>

 

방법3. 상위요소 선택 후 on 메소드 이용하는 방법

$("상위요소선택자").on("이벤트명","하위요소선택자(이벤트를걸고자하는요소),function(){

     선택된 상위 요소 안에 존재하는 하위요소에 해당 이벤트 발생시 실행할 내용;

     (이걸 꼭 써야하는 경우가 있음 ! )

}")

 

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

    <h5>div 바깥쪽 h5</h5>

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

            $(document).on("click","h5",function(){
                $(this).css("color","pink");
            });
        })
    </script>
 <!-- 무조건 3번 방법으로 해야하는 경우!! -->

    <h3>* 동적으로 만들어진 요소에도 동일한 이벤트를 적용시키고자 한다면 반드시 방법3으로 해야됨!!!</h3>
    <!-- 동적으로 만들어진 요소 : 처음에는 문소로딩시에는 없다가, 이벤트에 의해서 나중에 새로이 만들어진 요소 -->

 

일회성 이벤트(one 메소드)

딱 한번만 실행됨

 

<script>
        $(function(){
            $("#test3").one("click",function(){
                alert("처음이자 마지막 이벤트 실행");
            });
        })
    </script>

동적으로 글자수 세기

150자 내외로 작성하시오

<textarea id= "content" cols="30" rows="10" style="resize: none;"></textarea>

    <br><br>

    <span id="count">0</span>/150

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

 

결과물