VScode/JQuery

[JQuery] event

hvoon 2022. 9. 9. 14:50

1. 이벤트 연결

-기존 (자바스크립)의 이벤트 연결은 태그 안의 onclick 등의 속성을 넣고 자바스크립트 함수를 연결해서 실행되게 하는 방식이라면 제이쿼리는 직접선택자와 이벤트 이름을 연결하고 익명함수로 동작을 정의해서 실행되게 함

-on()

 

-사용 형태

1) $(selector).on(eventName,function(event){});

-selctor에 eventName이 발생하면 function(event){} 함수 실행

-$(function(){//h1에 'click'이 발생하면 function(event){} 실행

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="script/jquery-3.6.0.js"></script>
    <script type="text/javascript">
        $(function(){
            $('h1').on('click',function(){
// h1 태그가 여러개인 상태에서 $('h1') 선택자를 사용하면, 
// 그 여러개의 h1 태그가 동시 선택되고, 
// 그들에게 인덱스(번호)가 자동으로 부여됨
// 몇번재 h1 태그를 클릭했는지 아래와 같이 얻어낼 수 있음

// $('h1').on('click',function(){}); 
// -> $('h1').click(function(){}); 간략하게 사용 가능

                var k=$(this).index();
                // $(this): 현재 클릭된 h1 태그
                $(this).html(function(index,html){return html+k;});
                // index: 클릭된 h1의 번호, 
                // html: 그 h1 태그가 갖고 있는 현재 내용
                // html에 k를 이어붙이기 한 내용이 리턴되면 
                // 그 값은 html() 함수의 값으로 사용됨
            });
        });
    </script>
</head>
<body>
    <h1>header-0</h1>
    <h1>header-1</h1>
    <h1>header-2</h1>
</body>
</html>
 
header-0 두 번 클릭, header-1 4번 클릭, header-2 6번 클릭

2) $(selector).on(object);

-두가지 이상의 이벤트와 그에 따른 실행 함수 지정

$(function(){
    $('h1').on( // 'click', function(){}
        {
            mouseenter: function(){$(this).addClass('reverse')},
            mouseleave: function(){$(this).removeClass('reverse')}
            // h1에 마우스가 올라가면 reverse 클래스를 추가, 
            // 밖으로 나가면 클래스 제거 
       }
    ); 
}); 
 

3) $(selector).hover(function(event){},function(event){});

-hover(): mouseenter 이벤트와 mouseleave 이벤트를 동시에 연결

$(function(){
    $('h1').hover(
        function(event){$(this).addClass('reverse');},
        function(event){$(this).removeClass('reverse');}
    );
}); 
// on 대신 hover, 이벤트 이름 안 쓰고 익명함수인 컴파로 구분하여 표현
 
 

 

2. 이벤트 제거

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="script/jquery-3.6.0.js"></script>
    <script type="text/javascript">
        $(function(){            
            $('h1').on('click', function(){  
                $(this).html('CLICK'); // 내용을 CLICK 으로 변경
                $(this).off(); // 이벤트 제거
            });
        });
    </script>
</head>
<body>
    <h1>header-0</h1>
    <h1>header-1</h1>
    <h1>header-2</h1>
</body>
</html>
 
 

 

3. 매개 변수 context

-$(selector,context)

-selector가 적용하는 범위를 한정

-특정 부분의 선택자를 선택하고 싶을 때 사용하는 매개변수

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="script/jquery-3.6.0.js"></script>
    <script type="text/javascript">
// 아래의 내용은 클릭된 div 안의 h1과 p를 따로 선택자로 쓰고자할 때
// 자손 선택자를 사용하고자 하는데, 
// 부모가 this라면... $('this h1')라고 쓰면 안됨
// this가 ''안에 들어가는 순간 this로 사용이 안됨. 
// 그냥 문자('this')로 인식
        $(function(){
            $('div').click(function(){
            // div 중 클릭된 div를 this로 표현
            // -> 아래는 h1 중 click된 div 속 h1을 저장함
                var header=$('h1',this).text(); 
                // h1들 중 클릭된 div 내부의 h1 내용(text)
                var paragraph=$('p',this).text(); 
                // p들 중 클릭된 div 내부의 p 내용(text)
                var k=header+":"+paragraph;
                $('body').append($('<h1>'+k+'</h1>'));
            });
        });
    </script>
</head>
<body>
    <div><h1>header1</h1><p>paragraph1</p></div>
    <div><h1>header2</h1><p>paragraph2</p></div>
    <div><h1>header3</h1><p>paragraph3</p></div>
</body>
</html>
 
div 1 두 번 실행, div 2 한 번 실행, div 3 한 번 실행

 

 

4. 이벤트 강제 발생

-$(selector).trigger(eventName);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="script/jquery-3.6.0.js"></script>
    <script type="text/javascript">
        $(function(){
            $('h1').click(function(){
                $(this).html(function(index,html){return html+'>';});
            }); // 클릭된 div 태그의 내용에 '>'를 추가
            setInterval(function(){
                $('h1').last().trigger('click'); // $('h1').last().click();
            },1000); // 3초마다 마지막 div를 클릭한 것처럼 
                     // 내용에 '>'를 추가
        });
    </script>
</head>
<body>
    <h1>Start: </h1>
    <h1>Start: </h1>
    <h1>TRIGGER</h1>
</body>
</html>
trigger 자동 실행

 

5. 마우스 이벤트

-click: 마우스 클릭할 때 이벤트 발생

-dbclick: 마우스 더블클릭할 때 이벤트 발생

-mousedown: 마우스 버튼을 누를 때 이벤트 발생

-mouseup: 마우스 버튼을 뺄 때 이벤트 발생

-mouseenter: 마우스가 요소의 경계 외부에서 내부로 이동할 때 발생

-mouseleave: 마우스가 요소의 경계 내부에서 외부로 이동할 때 발생

-mousemove: 마우스가 움질일 때 발생

-mouseout: 마우스가 요소를 벗어날 때 발생

-mouseover: 마우스가 요소 안에 들어올 때 발생

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="script/jquery-3.6.0.js"></script>
    <script type="text/javascript">
        $(function(){
            $('.outer').mouseover(function(){
                $('body').append('<h3>mouseOver</h3>');
            }).mouseenter(function(){
                $('body').append('<h3>mouseEnter</h3>');
            });
        });
    </script>
</head>
<body>
    <div class="outer">
        <div class="inner">mouse controll</div>
    </div>
</body>
</html>
 
(右)mouse controll 위에 마우스를 올리면 생성되는 화면
 

 

6. 키보드 이벤트

-keydown: 키보드가 눌러질 때 발생

-keypress: 글자가 입력될 때 발생(한글지원 안됨)

-keyup: 키보드가 떼어질 때 발생

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="script/jquery-3.6.0.js"></script>
    <script type="text/javascript">
        $(function(){
            $('textarea').keyup(function(){
               var inputlegth=$(this).val().length; 
               // textarea에서 글자를 얻어 글자갯수 지정
               // val(): text(), html()과 비슷한 함수로 
               // 주로 input type 태그들을 대상을 할 때 사용함.
               // textarea는 input 태그와 동일한 용도로
               // 많이 사용되므로 val()로 값을 얻음.
               var remain=10-inputlegth; // 글자수 계산
               $('h1').html(remain); // 남은 글자 표시
               if(remain>=0) $('h1').css('color','black'); 
                                                // 양수는 검정
               else $('h1').css('color','red'); // 음수는 빨강
            });
        });
    </script>
</head>
<body>
    <div><p>지금 내 생각을</p><h1>10</h1>
        <textarea cols="70" rows="5"></textarea>
        <!-- <input type="textarea" value=""> 이 사용이 태그의 특성상 불편함으로 시작태그와 끝태그를 사용함 -->
    </div>
</body>
</html>