본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/JQuery

jQuery 적용하기 (파일 다운로드, CDN 방식)

by 차누감 2019. 12. 18.

JQuery를 사용하는 이유는 단축된 문법, 멀티브라우저 지원이다.

우선 JQuery 파일을 다운 받자. 아래 사이트에서 받을 수 있다.

https://jquery.com/

 

jQuery

What is jQuery? jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

jquery.com

다운로드를 누르면 개발환경에 따른 많은 파일들이 보인다. 

예제에서는 네모 영역의 파일을 사용하겠다.

저장할때 마지막에 .js를 붙여주고 자신이 원하는 위치에 저장하자.

작업하는 파일과 같은 공간(같은 폴더)에 넣었다.

(미리 01_ex.hrml 파일을 만들었다.)

이제 html파일에서 JQuery Livrary를 추가하자.

JQuery 문법은  JQuery를 쓰지만, 약식으로 $로 대체할 수 있다.

ready는 body load후 실행되도록 하는 것으로 우선 인식하자. (스크립트가 보통 head에 있기때문에 순서 문제를 방지)

이제 JQuery Livrary를 추가하는 두 번째 방법을 알아보자. CDN 방식

jquery 사이트에서 다운로드를 누르고 열리는 페이지에서 밑으로 내리다 보면 해당 글이 보일 것이다.

버튼을 누르면, 새로운 다이얼로그창을 띄어보자.

버튼 3개를 만들고, 클릭 이벤트를 사용해보자.

hide 버튼을 클릭했을때, 글씨를 hide(안보이게) 시키자.

2번째 버튼은 보이게, 3번째 버튼은 toggle을 주자.

hide 버튼을 눌러서 안보이는 p요소를 show 버튼을 누르면 보인다.

toggle 버튼을 누를때마다, 사라지고 다시 누르면 보이고 반복

이제 마우스 이벤트에 대한 것을 알아보자.

특정 영역에 마우스를 올리면, text를 보여주자. 그리고 특정 영역을 나가면 숫자를 카운트 한다. 

멀티 이벤트 처리를 알아보자. 우선 div로 네모 영역을 만들어 주자.

여러개의 이벤트를 하나의 객체로 만들어서 처리 가능하다.

마우스가 눌렸을때, 움직일때 등 내용을 똑같이 표시 해보자.

아래 사진과 같이 중복된 내용일때, 여러 이벤트를 한번에 처리 가능하다.

포커스에 대한 이벤트를 알아보자.


<복붙용 코드>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JQueery Library</title>
 
    <!-- JQuery Library추가 : www.jquery.com -->
    <!-- 1. 파일 다운로드 방식 -->
    <!-- <script src="./jquery-3.4.1.min.js"></script> -->
    <!-- 2. CDN(Content Delivery Network) 방식 -->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <!-- Google CDN : w3schools 사이트에서 권장하는 방식 -->
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> -->
 
    <script>
 
        // jquery : HTML요소를 찾을때 CSS선택자를 이용해서 쉽게 선택할 수 있음.
        // 문법
        // jQuery('css선택자 or 객체').xxx()  <-원래는 이렇게 씀. 근데 길어서 밑에 처럼 약식 표현함
        // $('css선택자 or 객체').xxx() //jQuery글씨가 길어서 $로 약식 표현
 
        // body요소가 load되었을 때 이벤트 처리
        $(document).ready( function(){
            // alert('aaa');
 
            jQuery('#btn').click( function(){
                alert('clicked');
                $(this).hide();
            });
 
            //JS의 addEventListener()와 같은 역할
            // 1. bind()
            $('#btn1').bind('click'function(){
                $('#p1').hide();
            });
 
            // 2. click()
            $('#btn2').click(function(){
                $('#p1').show();
            });
 
            // 3. on() : 권장
            $('#btn3').on('click',function(){
                // $('#p1').toggle();
                // $('p').toggle(); // 타입 선택자는 여러개일 수도 있음.[여러개가 동시에 적용]
                // $('p')[0].toggle(); //이렇게 하면 에러..why? [0]때문에 jquery가 아니므로
                // $($('p')[0]).toggle();
 
                // 참고
                // jquery변수를 일반 JS변수에 대입하면 일반 변수도 jquery변수처럼 사용가능
                var a= $('p');
                // a.toggle();
 
                // 일반 구별이 잘 안가서 .. 일부러 일반변수명에 $를 추가 시킴
                var e= $('p');
                $e.toggle();
 
            });
        });
    </script>
 
    <!-- 마우스 이벤트 연습을 위한 스타일 -->
    <style>
        div.m{
            width: 200px;
            height: 80px;
            background-color: yellow;
        }
        div.m2{
            width: 300px;
            height: 400px;
            background-color: teal;
        }
    </style>
 
    <script>
        $(document).ready( function(){
 
            $('.m').mouseover(function(){
                $('div.m p:first').text('mouse over');
            });
 
            var cnt =0;
            $('.m').on('mouseleave'function(){
                cnt++;
                $('div.m p:last').text(cnt);
            });
 
            // 여러개의 이벤트를 한번에 처리하기(객체로 만들어서..)
 
            var callbacks={
                mousedown:function(){
                    $(this).html('down : '+event.buttons+'<br>');
                    $(this).append('client or page : '+event.clientX+","+event.clientY+'<br>');
                    $(this).append('screen or page : '+event.screentX+","+event.screenY+'<br>');
                    $(this).append('offset or page : '+event.offsetX+","+event.offsetY+'<br>');
                },
                mousemove:function(){
                    $(this).html('move : '+event.buttons+'<br>');
                    $(this).append('client or page : '+event.clientX+","+event.clientY+'<br>');
                    $(this).append('screen or page : '+event.screentX+","+event.screenY+'<br>');
                    $(this).append('offset or page : '+event.offsetX+","+event.offsetY+'<br>');
                },
                mouseup:function(){
                    $(this).html('up : '+event.buttons+'<br>');
                    $(this).append('client or page : '+event.clientX+","+event.clientY+'<br>');
                    $(this).append('screen or page : '+event.screentX+","+event.screenY+'<br>');
                    $(this).append('offset or page : '+event.offsetX+","+event.offsetY+'<br>');
                },
                mousewheel:function(){
                   $(this).append( event.wheelDelta+"<br>"); //올리면 120, 내리면 -120
                }
            };
            $('div.m2').on(callbacks);
 
            // 한번에 처리하는 또다른 방식... 이방식을 더 많이 사용
            $('div.m2').on("mousedown mousemove mouseup"function(){
                $(this).append(event.type+'<br>');
            });
 
            // on메소드는 간소화만을 목적으로 하지 않음...
            // 브라우저 호환성을 목적으로도 권장됨
            // mousewheel은 firefox브라우저에서는 인식 안됨
            $('div.m2').on('mousewheel DOMMouseScroll'function(e){
                //DOMMouseScroll는 firefox브라우저의 휠이벤트임
                if(e.detail) $(this).append("변화 : "+emdelta+"<br>");
                else $(this).append("변화 : "+e.wheelDelta+"<br>");
            });
 
        });
    </script>
 
    <script>
        //포커스 이벤트 처리
        $(document).ready(function(){
            // input요소의 포커스 이벤트
            $('input').focus(function(){
                $(this).css('background-color','yellow');
            });
            $('input').on('blur'function(){
                $(this).css('background-color','');
            });
        });
    </script>
 
</head>
<body>
 
    <button id="btn">button</button>
 
    <hr>
    <h3>클릭 이벤트 처리 3가지 방법</h3>
    <button id="btn1">hide</button>
    <button id="btn2">show</button>
    <button id="btn3">toggle</button>
    <p id="p1">이 요소를 제어합니다.</p>
 
    <hr>
    <h3>마우스 이벤트</h3>
    <div class="m">
       <p></p>  <!-- 마우스 over 정보 -->
        <p></p> <!-- 마우스 leave 정보 -->
    </div>
 
    <hr>
    <!-- 멀티이벤트 처리 -->
    <div class="m2">
    </div>
 
    <hr>
    <h3>포커스 이벤트 처리</h3>
    <label>name : <input type="text"></label>
    
</body>
</html>
 

댓글