jquery 기초 정리 및 예제 :: 소림사의 홍반장!

jquery 기초 정리 및 예제

2012. 9. 11. 01:19 - 삘쏘굿

[참고]  bigwav's design http://bigwav.tistory.com/270

[참고] http://w3schools.com

 

 1. jQuery 개요

  -개요 : 자바 스크립트 라이브러리

 -엘리먼트 하나하나 접근하여 작업을 수행

 -일정 패턴을 반복

   -페이지에 강력한 CSS를 추가

 -엘리먼트 속성 변경, 엘리먼트를 추가

 

  -특징 : DOM 엘리먼트셀렉터(DOM: HTML, XML을 제어)

 태그 : $("a"),$("div")

 클래스 : $(".클래스명"), $("태그, 클래스명")

   ID : $("#id") --> document.getElementById("id")와 같다

 중첩구조 : $("#id").find("li") => $("#id li")

 

 

 jquery 사용

<script type="text/javascript" src="jquery.js"></script>

Please note that the <script> tag should be inside the page's <head> section.


 

 -Ajax 지원

 -Plugin 지원

 -단순화된 이벤트 처리

 -브라우저별 호환성 지원


 *jQuery(callback)/$(callback)

   $(document).ready(callback) 의 단축형


  $(document).ready(function(){

   //소스

  });


  $(function() {

 //소스

  });


  jQuery(document).ready(function() {

 //소스

  });


  jQuery(function() {

 //소스

  });

 


2. Core

  -jquery의 핵심이 되는것을 의미한다 core를 표현하면 '$()' 이렇게 된다


  1) jQuery( expression, context )

     expression는 String로 표현되고 특정 태그를 찾을때 사용되며, context는 Element나 jQuery으로 인자 값으로 받는다.

     즉, $("input:radio", document.forms[0]); 이와 같이 사용된다.


  2) jQuery( html )

     jQuery는 인자값으로 html 태그를 받아 그 태그를 HTML페이지에 추가를 할 수가 있다.

     즉, 이렇게 $("<div><p>제이쿼리</p></div>").appendTo("body") 사용이 되기도 하고,  

     $("<input/>").attr("type", "checkbox"); 이렇게 사용되기도 한다


  3) jQuery( elements )

     DOM element(s) 를 인자로 받아 그 지역의 elements를 설정할 수가 있다.(한개 혹은 다수를 지정할 수가 있다.)

     $(document.body).css( "background", "black" ); -> HTML 배경색을 검정색으로 바꾼다.

     $(myForm.elements).hide() -> myForm의 이름을 가진 form안의 elements을 숨긴다.


  4) jQuery( callback ) 인자값을 함수로 지정을 할 수가 있다

     "$(document).ready(function(){....};)"


  5) each( callback ) 해당 오브젝트에서 어떤 함수처리를 하고 싶을 경우 사용된다

     $(function() {

$(document.body).click(function(){

    $("div").each(function(args) {

//....

    });

});

     });


  6) size() 해당 오브젝트의 Elements의 수를 알고자 할 때 사용된다.

     $(document.body).click(function () {

        $(document.body).append($("<div>"));

        var n = $("div").size();

        $("span").text("There are " + n + " divs." + "Click to add more.");

    }).click(); // trigger the click to start


  7) length() 해당 오브젝트의 Elements의 수를 알고자 할 때 사용된다. size()와 동일하다.

      $(document.body).click(function () {

           $(document.body).append($("<div>"));

           var n = $("div").length;

           $("span").text("There are " + n + " divs." + "Click to add more.");

      }).trigger('click'); // trigger the click to start


  8) eq( position ) 해당 포지션에 위차한 태그를 찾는다.

  

  9) get()해당 태그의 Elements 들을 Array형태로 리턴한다. 즉, '$("div").get()' 하면 모든 div태그 들을 Array 형태로 리턴한다.

     한마디로 하면 DOM의 Elements를 배열로 리턴하는 것이다


      function disp(divs) {

          var a = [];

          for (var i = 0; i < divs.length; i++) {

               a.push(divs[i].innerHTML);

          }

          $("span").text(a.join(" "));

      }

      disp( $("div").get().reverse() ); // div태그의 값들을 읽어 와서 그 값의 순서를 뒤집는다.


 

 

3. Selectors(선택자)

Syntax Description
$(this) Selects the current HTML element
$("p:first") Selects the first <p> element
$(".intro") Selects all elements with class="intro"
$("#intro") Selects the first element with id="intro"
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
$("[href]") Selects all elements with an href attribute
$("[href$='.jpg']") Selects all elements with an href attribute that ends with ".jpg"
$("[href='#']") Selects all elements with an href value equal to "#"
$("[href!='#']") Selects all elements with an href value NOT equal to "#"
$("div#intro .head") Selects all elements with class="head" inside a <div> element with id="intro"

 

//ID

$("#div1").css("border", "3px solid red");

//element

$("p").css("color","blue");

//class

$(".test").css("color", "green");

//*: 모든요소

$("*").css("font-size", "15pt");

//계층적(조상의 자손)

$("form input").css("border", "2px solid blue");

//계층적(조상의 1단계 자손만)

$("#main > *").css("border", "3px double red");

//앞뒤 원소에 매치되는 뒤원소

$("label + input").css("color", "red").val("뭐냐");//val = value


* 모든 엘리먼트를 의미한다.

E 태그명이 E인 요소

E:nth-child(n) 부모 요소를 기준으로 n번째 위치한 요소

E:first-child 부모 요소를 기준으로 첫번째 위차한 요소

E:last-child 부모 요소를 기준으로 마지막에 위치한 요소

E:only-child 부모 요소를 기준으로 자식 요소가 하나인 요소

E:empty 자식 요소를 갖지 않은 요소.

E:enabled disabled 속성을 갖지 않은 요소.

E:disabled disabled 속성을 갖는 요소.

E:checked checked 속성을 갖는 요소.

E:selected selected 속성을 갖는 요소

E.className class 속성 값이 className인 요소

E#elId id 속성 값이 elId인 요소

E:not(s) 셀렉터 s를 제외한 요소

E F E 요소를 상위 노드로 갖는 F 요소

E > F E 요소를 부모노드로 갖는 F 요소

E + F E 요소를 앞의 위치에 가진 F 요소

E ~ F E 요소를 아래 위치에 가진 F 요소

E,F,G 모든 E 요소, F 요소, G 요소

E[@foo] 속성명으로 foo를 갖는 요소

E[@foo=bar] 속성명이 foo이면서 속성값이 bar인 요소

E[@foo^=bar] 속성명이 foo이면서 bar 속성값이 bar로 시작하는 요소

E[@foo$=bar] 속성명이 foo이면서 bar 속성값이 bar로 끝나는 요소

E[@foo*=bar] 속성명이 foo이면서 bar 속성값이 bar를 포함하는 요소

E[@foo=bar][@baz=bop] 속성명이 foo이면서 bar 속성값이 bar이고, 속성명이 baz이면서 속성값이 bop인 요소

:even 짝수 번째인 요소를

$("tr:even").css("background", "#00FF00");

:odd 홀수 번째인 요소를

$("tr:odd").css("background", "#FF0000");

:eq(n) 또는 :nth(n) n번째에 해당하는 요소

$("tr:eq(2)").css("color", "silver");

:gt(n) n+1번째 보다 큰 요소

$("tr:gt(3)").css("color", "red");

:lt(n) n+1번째 보다 작은 요소

:first 또는 :eq(0) 첫번째 요소

$("tr:first").css("background", "#FFFF00").css("color", "blue");

:last 마지막 요소

$("tr:last").css("background", "#00FFFF");

:parent 대상 요소의 부모 요소

:contains('문자열') text 노드값에 '문자열'을 포함하는 요소

$("tr:contains('홍')").css("border", "solid 3px green");

:visible display:none이 아닌 요소

:hidden display:none인 요소

:input 또는 :select 폼과 관련된 요소. (input, select, textarea, button)

:text input type이 text인 요소

:password input type이 password인 요소

:radio input type이 radio인 요소

:checkbox input type이 checkbox인 요소

:submit input type이 submit인 요소

:image input type이 image인 요소

:reset input type이 reset인 요소

:button input type이 button인 요소

:file input type이 file인 요소




4. Attributes(속성)

        $("#btn2").click(function(){  // 속성 확인하기 

//var title=$("p").attr("title");

//alert(title);

var str=$("#name").attr("type");

alert(str);

});

$("#btn3").click(function(){  // 속성 추가하기

$("#name").attr("disabled","disabled"); //버튼을 클릭하면 이름변경불가속성 추가...

});

$("#btn4").click(function(){  // 속성 삭제하기

$("#name").removeAttr("disabled");

});

$("#btn5").click(function(){  

$("p:even").removeClass("blue"); //짝수번째 클래스 삭제

$("p:first").addClass("under"); //p태그 첫번째...라인 삽입

});

$("p").click(function(){

$(this).toggleClass("bk"); //토글주기... p태그의 bk스타일 토글 

});

$("#btn6").click(function(){  

var s = $("#div1").html();  //html태그 가져오기.

alert(s);

});

$("#btn7").click(function(){  

var s = $("#div1").html("<input type='text'/>");   //html input태그 변경

alert(s);

});




5. Manipulation(조작)

  내부삽입

 1.append(content) - 모든 요소 내부에 컨텐츠를 추가한다.

$("p:first").append("<b>hello</b>");

 2.appendTo(content) - 요소의 내용을 다른 요소에 추가한다.

$("span").appendTo("#div1");

 3.prepend(content) - 모든 요소 내부의 선두에 컨텐츠를 삽입한다.

$("p").prepend("<b>앱</b>");

 4.prepend(content) - 요소의 내용을 다른 요소에 추가한다.

  외부삽입

 1.after(content) - 각 요소의 뒤로 컨텐츠를 삽입한다

 2.before(content) - 각 요소의 전에 컨텐츠를 삽입한다.

 3.insertAfter(content) - 요소를 지정한 다른 요소의 뒤에 삽입한다.

 4.insertBefore(content) - 요소를 지정한 다른 요소의 전에 삽입한다.

  주위에의 삽입

 1.wrap(html) - 각 요소를 구조적으로 지정HTML그리고 둘러싼다.

 2.wrap(elem) - 각 요소를 구조적으로 지정 요소로 둘러싼다.

 3.wrapAll(html) - 각 요소를 한덩어리로 해 1개의 HTML 지정 요소로 둘러싼다.

 4.wrapAll(elem) - 각 요소를 한덩어리로 해 1개의 지정 요소로 둘러싼다.

 5.wrapInner(html) - 요소가 가지는 각자요소(텍스트 포함)를 HTML 지정 요소로 둘러싼다.

 6.wrapInner(elem) - 요소가 가지는 각자요소(텍스트 포함)를 지정 요소로 둘러싼다.

  치환

 1.replaceWith(content) - 각 요소를 지정 HTML 혹은 DOM Element 그리고 옮겨놓는다.

 2.replaceAll(selector) - 지정 조건에 합치하는 요소를 모두 옮겨놓는다.

  삭제

 1.empty() - 요소 집합으로부터 모든 아이 요소를 삭제한다.

 2.remove([expr]) - DOM으로부터 지정 조건에 합치하는 요소를 모두 삭제한다.

  카피

 1.clone() - DOM요소를 카피해 새롭게 작성

 2.clone(true) - DOM요소를, 그 요소가 가지는 이벤트도 포함해 카피한다.

 

jQuery css() Method

jQuery has one important method for CSS manipulation: css()

The css() method has three different syntaxes, to perform different tasks:

  • css(property) - Return CSS property value
  • css(property,value) - Set CSS property and value
  • css({properties}) - Set multiple CSS properties and values

 

 

 

 

 

6. jQuery Events

 

Event Method Description
$(document).ready(function) Binds a function to the ready event of a document
(when the document is finished loading)
$(selector).click(function) Triggers, or binds a function to the click event of selected elements
$(selector).dblclick(function) Triggers, or binds a function to the double click event of selected elements
$(selector).focus(function) Triggers, or binds a function to the focus event of selected elements
$(selector).mouseover(function) Triggers, or binds a function to the mouseover event of selected elements


  $("#btn1").bind("click", function(event){

alert("안녕!!");

  })

 

  .bind("mouseover", function(event){

alert("안녕!!");

  });


  //이미지위에 마우스가 올려졌을때 그림이 바뀐다

  $("#img1").mouseover(function(){

$(this).attr("src","<%=cp%>/img/2.jpg");

  });

  //이미지위에 올린 마우스를 떼면 원상태로 돌아간다

  $("#img1").mouseout(function(){

$(this).attr("src","<%=cp%>/img/1.jpg");

  });

  //이벤트가 한번 실행되고 해제

  $("#btn3").one("click",function(){

alert("..............");

  });



  .blur()

 요소에서 포커스를 잃을 경우에 발생하는 이벤트 입니다.

 .change()

 <input />, <textarea />, <select /> 요소의 값 변경시 발생하는 이벤트 입니다.

 .click()

 마우스 클릭 시 발생하는 이벤트 입니다.

 .dblclick()

 마우스를 더블클릭 했을 경우 발생하는 이벤트 입니다.

 .focus()

 요소에 포커스 되었을 때 발생하는 이벤트 입니다.

 .hover()

 마우스가 요소 위에 위치했을 때 발생하는 이벤트 입니다.

 .keydown()

 키 입력 시 발생되는 이벤트이며, 모든 키에 대해 적용이 됩니다.

 .keypress()

 keydown 이벤트와 동일하게 키 입력 시 발생이 되지만 

 enter, tab등의 특수키에는 이벤트가 발생되지 않습니다.

 .keyup()

 키 입력 후 발생되는 이벤트 입니다.

 .mousedown()

 마우스 클릭 시 발생하는 이벤트입니다.

 .mouseenter()

 선택한 요소의 영역에 마우스가 위치했을 때 발생되는 이벤트 입니다.

 .mouseleave()

 선택한 요소의 영역에서 마우스가 벗어 났을 때 발생되는 이벤트 입니다.

 인터넷익스플로러에서만 발생되는 이벤트지만 jQuery는 브라우저 관계없이 

 사용할 수 있도록 시뮬레이터 됩니다.

 .mouseout()

 선택한 요소의 영역에서 마우스가 벗어 났을 때 발생되는 이벤트입니다.

 .mouseup()

 마우스 클릭 후 발생되는 이벤트입니다.

 .ready()

 DOM이 모두 준비 되었을 때 발생하는 이벤트입니다.

 .resize()

 resize 될 경우 발생하는 이벤트입니다.

 .scroll()

 HTML 문서가 스크롤 되었을 때 발생하는 이벤트입니다.

 .select()

 선택한 개체를 마우스를 통해 선택 하였을 때 발생하는 이벤트입니다.

 .submit()

 Submit이 일어날 때 발생하는 이벤트입니다. (Form 메서드 참고)

다른 카테고리의 글 목록

Dev. 웹/JavaScript 카테고리의 포스트를 톺아봅니다