본문 바로가기

도구의발견

jQuery 사용하기

1. jQuery CDN 연결

jQuery 자바스크립트를 다운 받고 서버에 다시 올리기 귀찮으니 구글과 MS에서 제공하는 CDN(Content Delivery Network)을 사용하도록 하자 :

Google CDN :

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

Microsoft CDN :

<head>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>

 

2. jQuery 문법 기본

$(selector).action()
  • '$' : jquery를 사용하겠다는 선언. jquery 객체 자체를 의미한다.
  • (selector) : html 엘리먼트를 찾고 접근하기 위한 selector
  • action() : 엘리먼트에 수행할 작업
  • jQuery selector는 css selector방식을 사용하고 있음. [진리는어디에/Web] - CSS Selectors 를 참고.
  • eg :
    • $(this).hide() - 현재 엘리먼트를 보이지 안도록 감추다
    • $("p").hide() - <p> 엘리먼트는 모두 보이지 않도록 감추다.
    • $(".test").hide() - class="test" 인 모든 엘리먼트를 보이지 않도록 감추다.
    • $("#test").hide() - id="test" 인 모든 엘리먼트를 보이지 않도록 감추다.

 

3. jQuery 예제

$(document).Ready(function() {
    // ...
});

 

jQuery Event

$(selector).click(function() {

});

* manual : https://www.w3schools.com/Jquery/jquery_events.asp

* reference : https://www.w3schools.com/Jquery/jquery_ref_events.asp

 

jQuery Effect :

$(selector).hide();

* manual : https://www.w3schools.com/Jquery/jquery_hide_show.asp

* reference : https://www.w3schools.com/Jquery/jquery_ref_effects.asp

 

jQuery HTML :

text() - Sets or returns the text content of selected elements

html() - Sets or returns the content of selected elements (including HTML markup). 위에꺼에 html도 같이 포함해서 리턴한다.

val() - Sets or returns the value of form fields. form에서 value에 매핑 된 값만 리턴한다.

attr() method is used to get attribute values.

 

append() - Inserts content at the end of the selected elements

 eg) ol 태그에 하위 li 태그를 append 할 수 있다

prepend() - Inserts content at the beginning of the selected elements

after() - Inserts content after the selected elements

before() - Inserts content before the selected elements

 

remove() - Removes the selected element (and its child elements)

empty() - Removes the child elements from the selected element

 

jQuery Traversing

* first()

* last()

* eq()

* filter() : https://www.w3schools.com/Jquery/jquery_filters.asp

* not()

* find()

 

jQuery AJAX(Asynchronous JavaScript and XML.)

* $(selector).load() : https://www.w3schools.com/Jquery/jquery_ajax_load.asp

* $.get(URL, callback)/$.post(URL, data, callback) : https://www.w3schools.com/Jquery/jquery_ajax_get_post.asp

* reference : https://www.w3schools.com/Jquery/jquery_ref_ajax.asp

 

부록 1 : jQuery 의 '$'는 무엇인가?

jQuery를 사용하는 코드를 보면 거의 모든 시작이 '$'로 시작 됨을 종종 볼 수 있다. 저게 뭘까? 왜 어떤 코드는 $(...) 처럼 쓰고 ajax를 사용 할때는 $.get과 같이 바로 사용하는 것일까? 궁금하다. 그래서 찾아 봤다.

window.jQuery = window.$ = jQuery;

jQuery 코드 내부를 살펴 보면 위와 같이 정의 되어 있다. 코드에서 사용하는 것은 결국 jQuery라이브러리의 객체이며 그 객체에 접근하는 방법 중 하나가 '$'를 사용하는 것이다. 만일 특정 엘리먼트에 접근하고 싶다면 $("#some-element-id") 가 될 것이고, ajax 처럼 jQuery 객체의 get 또는 post 함수를 호출하는 것이다.

$('div').css(...) 와 jQuery.('div').css(...)는 동일한 의미를 같는 코드다(일반적으로 window는 생략 된다)

유익한 글이었다면 공감(❤) 버튼 꾹!! 추가 문의 사항은 댓글로!!