JQuery 기본적인 사용방법.

dom 선택

css selector와 같은 형식으로 dom을 선택할 수 있다. selector를 사용하기 위해서 jQuery 혹은 $를 사용한다.

  1. jQuery("#id")  
  2. $(".class")  
  3. $("tag.class")  

return되는 것은 jQuery 객체이다.

 

event handling

가장 맘에 드는 event handling이다. 다음과 같이 선택된 DOM에 원하는 event 함수들을 달아놓으면 된다.

  1. $(document).ready( function() {  
  2.   $("#project_submit").click(function(){    
  3.     alert("submit the form");  
  4.     return true;  
  5.   });  
  6. });  

$(document).ready 는 브라우져가 모든 js 들을 다 download 받은 후 실행될 것을 보장한다. (window.onload와 같다.)

$("#project_submit").click 은 project_submit이란 id를 가진 dom에 click 이벤트가 발생하면 실행된다.

더 자세한 event에 대해서는 http://docs.jquery.com/Events 를 참조한다.

Effect

간단한 effect들 역시 손쉽게 사용할 수 있다.

  1. $("#message_box").fadeOut();  

더 자세한 효과들에 대해서는 http://docs.jquery.com/Effects 를 참조.

 

each, map, unique

배열이 있고 배열을 iteration 하고 싶은 경우 each를 사용할 수 있다.

  1. members = ["juddy""james"];  
  2. $.each(members, function() {  
  3.   project.members.push(this));  
  4.   
  5. });  

function 안의 this는 각 member를 가르킨다.

selector를 이용했다면 다음과 같이 더 간결한 표현도 가능하다.

  1. $(".project").each( function() {    
  2. });  

 

Ajax Request

Ajax request도 간단하게 사용할 수 있다.

  1. $.ajax({  
  2.   type: "POST",  
  3.   url: "/projects/recent",  
  4.   data: "duration=5&user=juddy",  
  5.   success: function(html){  
  6.    $("#recent_projects").replaceWith(html);  
  7.   }  
  8. });  

success는 요청 성공시 호출되는 event handler이다. 이렇게 각 요청에 대해서 event handler를 작성할 수도 있고, 모든 요청에 대한 global event handler를 다음과 같이 정의할 수도 있다.

  1. $("#ajax_msg").ajaxSuccess(function(evt, request, settings){  
  2.    $(this).append("<li>Successful Request!</li>");  
  3.  });  

 

json request를 callback과 함께 사용하고 싶다면 getJSON을 사용할 수도 있다. (GET요청만 사용가능)

  1. $.getJSON("/projects/recent",  
  2.   function(data){  
  3.     // handle data  
  4.   });  
  5. });  

 

더 자세한 내용은 http://docs.jquery.com/Ajax 를 참조.