'07.JavaScript, jQuery, ExtJS...'에 해당되는 글 73건

  1. 2010.02.19 Create and append text node
  2. 2010.02.19 Add Text node created by document
  3. 2010.02.19 Append HTML to
  4. 2010.02.19 Append HTML to
  5. 2010.02.19 Add and remove text paragraph
  6. 2010.02.19 Add click listener to links in unordered list
  7. 2010.02.19 Stop click event
  8. 2010.02.19 Find all children of the clicked element.
  9. 2010.02.04 jquery 간단한 ajax
  10. 2009.10.16 eclipse 3.5 aptana plugin
  11. 2009.10.16 [jQuery] layout, tab, grid
  12. 2009.07.07 자바스크립트 라이브러리 Jquery 플러그인
  13. 2009.03.09 jQuery로 작업하기, Part 2: 내일 나올 웹 응용을 오늘 구현해보자
  14. 2009.03.09 가볍고 쉬운 Ajax - jQuery 시작하기
  15. 2009.03.09 Ajax로 사이트 전면 개편, Part 3: jQuery, Ajax 탭, 회전식 슬라이드쇼로 기존 사이트 개선하기
  16. 2009.03.09 jQuery로 작업하기, Part 1: 브라우저로 데스크톱 응용 옮기기
  17. 2009.03.09 jQuery and Google Maps Tutorial: #1 Basics
  18. 2009.03.09 JQuery Core 1
  19. 2009.03.09 간단한 jQuery 시작하기 자료
  20. 2009.03.09 jQuery Download...
  21. 2009.03.09 jQuery 를 사용하면서 ASP.NET 서버컨트롤와 절묘하게
  22. 2009.03.09 jquery 플러그인 링크
  23. 2009.01.28 jQuery Core 기본예제
  24. 2009.01.28 Google AJAX Libraires API를 이용해서 자바스크립트 프레임워크 사용하기 3
  25. 2009.01.08 [ExtJs] 튜토리얼 1
  26. 2009.01.08 Ext 2.0 Tutorial Introduction
  27. 2009.01.08 ExtJS 개발하기 위해 선행되는 지식들 :: Scripter/EXTJS 1
  28. 2009.01.08 ExtJs 공식 블로그에 Intergrating Google Maps API With ExtJS 라는 글이 포스팅
  29. 2008.11.19 MooTools Mocha UI v0.5
  30. 2008.11.19 깜찍한 캘린더 - MooTools Calendar Component
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("div").html("<b>bold</b> not bold");
            $("div b").append(document.createTextNode("!!!")).css("color", "red");
        });
    </script>
  </head>
  <body>
    <body>
      <DIV></DIV>
  </body>
</html>
Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
               $("p").html("<b>bold</b>");
               $("p b").append(document.createTextNode("added")).css("color", "red");
        });
    </script>
  </head>
  <body>
    <body>
         <p>asdf</p>

  </body>
</html>

Posted by 1010
반응형

<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             $("p").append("<strong>Hello</strong>");

        });
    </script>
  </head>
  <body>
    <body>
         <p>asdf</p>
         <p>asdf</p>
         <p>asdf</p>
         <p>asdf</p>
  </body>
</html>

Posted by 1010
반응형

<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             $("p").append("<strong>Hello</strong>");

        });
    </script>
  </head>
  <body>
    <body>
         <p>asdf</p>
         <p>asdf</p>
         <p>asdf</p>
         <p>asdf</p>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <style type="text/css">
        a.test { font-weight: bold; color:red;}
    </style>

    <script type="text/javascript">
 $(document).ready(function(){

    $("input.buttonA").click(function(){$("div.contentToChange").find("p").not(".alert").append("<strong>&nbsp;Appended</strong>")});
    $("input.buttonB").click(function(){$("strong").remove()});


 });

    </script>
  </head>
  <body>
    <input type="button" value="Add" class="buttonA" />
    <input type="button" value="Remove" class="buttonB" />


    <div style="background:#eee;" class="contentToChange">
        <h2>Header 2</h2>
       
        <p class="firstparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
       
        <p class="secondparagraph">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse <strong>molestie</strong> consequat, vel illum <strong>dolore</strong> eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer <strong>adipiscing</strong> elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
       
        <p class="thirdparagraph">Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea <em>commodo</em> consequat. Duis autem vel eum iriure dolor in hendrerit in <em>vulputate</em> velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te <strong>feugait</strong> nulla facilisi.</p>
       
        <p class="fourthparagraph">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, <strong>quis</strong> nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
       
        <p class="fifthparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
       
        <p class="sixthparagraph">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse <strong>molestie</strong> consequat, vel illum <strong>dolore</strong> eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer <strong>adipiscing</strong> elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
       
    </div>

  </body>
</html>


Posted by 1010
반응형

<html>
  <head>
    <script type='text/javascript' src='js/jquery-1.3.2.js'></script>
    <script type='text/javascript'>
var tmpExample = {
  ready : function() {
    $('ul#myStyle li a').click(
      function($e) {
        $e.preventDefault();
        window.open(this.href, 'FavoriteLink', '');
      }
    );
  }
};

$(document).ready(tmpExample.ready);

    </script>
    <style type='text/css'>
ul {
    list-stlye: none;
    margin: 0;
    padding: 0;
}
a {
    text-decoration: none;
}
    </style>
  </head>
  <body>
    <ul id='myStyle'>
        <li><a href='http://www.java2s.com'>java2s</a></li>
        <li><a href='http://www.apple.com'>Apple</a></li>
        <li><a href='http://www.jquery.com'>jQuery</a></li>
    </ul>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type='text/javascript' src='js/jquery-1.3.2.js'></script>
    <script type='text/javascript'>
var tmpExample = {
  ready : function() {
    $('ul#myStyle li a').click(
      function($e) {
        $e.preventDefault();
        window.open(this.href, 'FavoriteLink', '');
      }
    );
  }
};

$(document).ready(tmpExample.ready);

    </script>
    <style type='text/css'>
ul {
    list-stlye: none;
    margin: 0;
    padding: 0;
}
a {
    text-decoration: none;
}
    </style>
  </head>
  <body>
    <ul id='myStyle'>
        <li><a href='http://www.java2s.com'>java2s</a></li>
        <li><a href='http://www.apple.com'>Apple</a></li>
        <li><a href='http://www.jquery.com'>jQuery</a></li>
    </ul>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
               
               $("#container").click(function (e) {
               
                  var $kids = $(e.target).children();
                  alert($kids.length);
           
           
                  e.preventDefault();
                  return false;
                });
                   

        });
    </script>
  </head>
  <body>
    <body>
        <div id="container">
        <div>
          asdf
        </div>
        </div>
         
    </body>
</html>

Posted by 1010
반응형

<%@ page language="java" contentType="text/html; charset=EUC-KR"
 pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script type="text/javascript" src="/js/jquery-1.4.min.js"></script>

<script type="text/javascript">
 $(document).ready(function() {
  $.ajax( {
   url : 'data.txt',
   type : 'GET',    
   dataType : 'txt', 
   timeout : 1000,
   error : function() {
    alert('Error loading XML document');
   },
   success : function(xml) {
    if(xml > 99){
     alert("99보다 크다 :"+xml);
    }else{
     alert("99보다 작다 :"+xml);
    }
  }
  });
 });
</script>

</head>
<body>
<div class="message">div</div>
</body>
</html>

Posted by 1010
반응형
Posted by 1010
반응형

Ext JS와 비교를 위해, jQuery로 비슷한 걸 만들어 본다. 필요한 건 대략 아래와 같다.

  1. layout
  2. tab
  3. grid
  4. window + form

하나씩, 찾아보자.


1. layout


http://layout.jquery-dev.net/

- Ext JS의 layout, viewport와 유사한 기능

- north, west, center, east, south 영역

- 뭐, 그럭저럭, 쓸 만 하다.





2. 탭 (tab)


http://jqueryui.com/demos/tabs/ 


- 테마(Theme) 설정에 따라, 컬러와 모양이 확 달라진다.

- 위의 것은 기본 테마인, Theme: UI lightness

- 아래 것은, Theme: Smoothness




http://flowplayer.org/tools/tabs.html

- 찾아보니, 좀 다른 것도 있다. 좀더 화려한 느낌이다.



3. grid


3.1. jqGrid


http://www.trirand.com/blog/


 


- Ext JS와 비교해서, 다소 불편.

- pager : 서버에 전달하는 파라미터, 영 신통치 않음. page, rows, sidx, sord. 서버에서 start, limit를 다시 계산해야 하는 번거로움.

- json 데이터를 뽑는 형식, 디폴트 형식이 아주 불편. colModel에 있는 것만 뽑을 수 있고, 순서도 지켜줘야 함.

- 좀더 자유롭게 뽑으려면, repeatitems: false 옵션으로  jsonReader를 재설정해줘야 함.

http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data

- 기본 출력형식도 영 꾸짐. jQuery의 특성, 기본은 꾸지고, 보기 좋게 하려면, css 손질을 해줘야 함. 그 대신, css 손질은 쉬운 편.

http://techbug.tistory.com/158

- Ext JS의 renderer와 유사한 기능을 하는 formatter 있슴. custom formatter 제작 가능. 컬럼의 출력형식 조정 가능.

function myformatter ( cellvalue, options, rowObject )
{
    // format the cellvalue to new format
    return new_formated_cellvalue;
}


- tab 에 grid를 붙이니까, 모양이 영 엉성하다. Ext JS에서는 tab의 title 부분이 싹 사라지고, grid의 title이 그 자리에 쏙 들어찼는데, 여기선, 영, 자기 자리들을 모두 굳건히 지키느라, 뭔가 착 달라붙어서 빈틈을 메워주는 느낌이 없다.


jqGrid + tab 조합



Ext JS, grid + tab 조합





3.2. flexigrid


http://www.flexigrid.info/ 좀더, 화려하고 정제된 기능. 얼핏 보면, Ext JS 닮았다. 툴바 기능. 검색기능.





- 좀 더 뜯어보니, 약점이 많다.

- json 포맷이 한 가지 밖에 없슴. jsonReader 재설정 기능 없슴. 무조건 데이터를 맞춰서 colModel에 뽑아야 함.

- colModel에 hide: true 속성이 있긴 하지만, 잠깐 숨기는 정도의 기능

- formatter 기능 설정이 안보임. 없나?

- 최종 변경일이 Jul 2008. 그 이후엔 업그레이드를 안하고 있는 듯.


3.3. 기타 grid


http://php-team.blogspot.com/2009/05/10-jquery-datagrid-plugins.html Grid Plugin 비교 설명

- 아무리 봐도, Ext JS의 Grid 만한 녀석은 없다.

- jQuery의 장점인 style, structure, behavior 분리가 오히려 어떤 점에서는 약점이 되기도 하는 느낌. 잘 만들어진 컴포넌트 느낌이 나질 않는다.



4. window + form


이 부분은, 나중에, 간단하게, 링크만 남겨둔다.





5. 참고자료


Posted by 1010
반응형

http://blog.naver.com/kusaltk/70026986513

 -Jquery 플러그인 모음 이거한방이면 끝..!! : http://www.seek-blog.com/41065/14090/240-plugins-jquery.html

 -light box(이미지 미리보기,pre,next) : http://leandrovieira.com/projects/jquery/lightbox/

 -이미지 스크롤 : http://benjaminsterling.com/2007/09/09/jquery-jqgalscroll-photo-gallery/

 -이미지 싸이클 : http://www.malsup.com/jquery/cycle/

 -BlockUI Plugin(processing,처리중 등등,confirm) :  http://www.malsup.com/jquery/block/#element

 -UI Modal : http://jquery.com/demo/thickbox/

 -플래쉬 플러그인 삽입 : http://jquery.lukelutman.com/plugins/flash/#examples

 -Photo Slider Tutorial : http://opiefoto.com/articles/photoslider#example

 -jScrollPane : http://kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html

 -Accessible News Slider  : http://www.reindel.com/accessible_news_slider/#examples

 - unobtrusive tabs(탭메뉴) : http://stilbuero.de/jquery/tabs/#fragment-29
      http://www.sunsean.com/idTabs/#t3

 -jQuery Ajax Link Checker : http://troy.dyle.net/linkchecker/

 -jQuery Form Plugin  : http://malsup.com/jquery/form/#code-samples

 -jquery.suggest, an alternative jQuery based autocomplete library(자동완성)
  http://www.vulgarisoip.com/2007/06/29/jquerysuggest-an-alternative-jquery-based-autocomplete-library/
  http://nodstrum.com/2007/09/19/autocompleter/

 -jlook(폼객체 리뉴얼)  :

  http://envero.org/jlook/

 -jQuery - LinkedSelect(멀티 select) :

  http://www.msxhost.com/jquery/linked-selects/json/

 -Masked Input Plugin    : (입력포맷 확인)
  http://digitalbush.com/projects/masked-input-plugin
  http://www.appelsiini.net/projects/jeditable/default.html

 -Overlabel with JQuery(박스안에 워터마킹처리)  : http://scott.sauyet.com/Javascript/Demo/Overlabel/

 -Styling an input type="file"(파일찾기 이미지 처리)
   http://www.quirksmode.org/dom/inputfile.html

 -jQuery UI Datepicker v3.0 Examples(달력)
  http://marcgrabanski.com/code/ui-datepicker/

 -jQuery Validation Plugin(폼체크,포커싱)
  http://jquery.bassistance.de/validate/demo-test/ 
  http://www.texotela.co.uk/code/jquery/focusfields/
 
 -jQuery columnHover plugin(컬럼 하이라이트/컬럼 컨트롤)
  http://p.sohei.org/stuff/jquery/columnhover/demo/demo.html
  http://p.sohei.org/stuff/jquery/columnmanager/demo/demo.html

 -tablesorterDocumentation(테이블 순서)
  http://tablesorter.com/docs/index.html 

 -jQuery Accordion Demo(컨테이너 예제)
  http://jquery.bassistance.de/accordion/?p=1.1.1

 -jQPanView based in jQuery 1.1(이미지 확대보기)
  http://projects.sevir.org/storage/jpanview/index.html

 -jQuery Impromptu(confirm,alert 등등)
  http://trentrichardson.com/Impromptu/

 -jqGrid Examples(그리드)
  http://trirand.com/jqgrid/jqgrid.html#

 -Toggle HTML-Elements with jQuery
  http://jquery.andreaseberhard.de/toggleElements/

 -UI/Sortables(테이블 위치변경 ^^)
  http://docs.jquery.com/UI/Sortables

 -뉴스 슬라이더(부분보기,전체보기)
  http://www.reindel.com/accessible_news_slider/

 -로컬 스크롤러
  http://www.freewebs.com/flesler/jQuery.LocalScroll/

 -핫키 테스트
  http://jshotkeys.googlepages.com/test-static.html

 -슬라이더
  http://docs.jquery.com/UI/Slider/slider

 -쇼핑카트
  http://www.mimul.com/pebble/default/2007/10/30/1193753340000.html

 -테이블 소트
  http://www.mimul.com/pebble/default/2007/11/06/1194348600000.html

 -이미지 나중에 로딩시키기
  http://www.mimul.com/pebble/default/2007/11/10/1194695220000.html

 -오토탭(입력시 폼객체 자동넘김)
  http://dev.lousyllama.com/autotab/

 -실시간 폼객체 수정
  http://www.appelsiini.net/projects/jeditable/custom.html

 -프린트
  http://www.designerkamal.com/jPrintArea/#
 -차트
  http://www.reach1to1.com/sandbox/jquery/jqchart/

 -CSS Dock Menu (Jquery + CSS)
  후니넷에서 보삼
 -툴팁
  http://www.codylindley.com/blogstuff/js/jtip/

 -XML데이터 뿌리기
  http://blog.reindel.com/src/jquery_browse/
  http://www.xml.com/pub/a/2007/10/10/jquery-and-xml.html
  http://www.mimul.com/pebble/default/2006/11/05/1162710000000.html

 -Clearing Form

  http://www.learningjquery.com/2007/08/clearing-form-data

 --암호 복잡성 체크

  http://phiras.googlepages.com/PasswordStrengthMeter.html

 --Form Serialize

  http://dev.jquery.com/wiki/Plugins/FastSerialize

 --GetString 퍼라미터 가져오기
  http://www.mathias-bank.de/2006/10/28/jquery-plugin-geturlparam/

 --검색 후 콤보생성(ajax with combo) 아주 유용함
  http://extjs.com/deploy/ext/examples/form/forum-search.html
  http://extjs.com/deploy/ext/examples/grid/edit-grid.html-->그리드

 --파일 업로드(input=file) 리폼
  http://www.appelsiini.net/projects/filestyle/demo.html

Jquery Best
 http://www.spicyexpress.net/general/jquerry-at-it-best-downloadable-jquerry-plugins-and-widgets-for-you-2/

웹디자인 템플릿트(2.0)
 -http://www.templateworld.com/free_templates.html

----------------------------------------
Jquery tag cloud
http://www.ajaxrain.com/tagcloud.php
Jquery 기본설명
http://www.zzbb.kr/34
----------------------------------------

^^Star Rater(순위) --활용가능성 높음
http://www.m3nt0r.de/devel/raterDemo/

^^ AJAX CALLING --활용가능성 높음
http://cgaskell.wordpress.com/2006/11/02/jquery-ajax-call-and-result-xml-parsing/

--AJAX 아이디 중복체크 - 활용가능성 아주높음
http://www.shawngo.com/gafyd/index.html

^^ jQuery framework plugins which provide a way to sort and nest elements in web applications, using drag-and-drop(테이블드래그앤드랍) --활용가능성 중간
http://code.google.com/p/nestedsortables/

^^Simple tableSorter(리스트 정렬) 활용가능성 중간
http://motherrussia.polyester.se/docs/tablesorter/

^^Cookie 활용가능성 높음
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/

^^태깅 --그냥한번보자..ㅎ
http://www.alcoholwang.cn/jquery/jTaggingDemo.htm

^^죽이는 어코디언 메뉴
http://dev.portalzine.de/index?/Horizontal_Accordion--print

^^ AJAX Indicator 이미지
http://qureyoon.blogspot.com/2006/11/make-your-own-loading-gif.html

----------------------------------------
2007.12.28 찾은것
----------------------------------------
http://rikrikrik.com/jquery/quicksearch/#usage
http://nadiaspot.com/jquery/confirm/#examples
http://host.sonspring.com/portlets/
http://jquery.andreaseberhard.de/toggleElements/
http://www.getintothis.com/pub/projects/rb_menu/
http://icon.cat/software/iconDock/0.8b/dock.html
http://www.nuernberg.de/internet/portal/index.html
http://rikrikrik.com/jquery/shortkeys/#examples
http://rikrikrik.com/jquery/pager/#examples
http://famspam.com/facebox/ --라이트박스같은것
http://www.andreacfm.com/
http://www.vulgarisoip.com/2007/06/29/jquerysuggest-an-alternative-jquery-based-autocomplete-library/ --autocomplete
http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html - 뉴스 스크롤
http://d-scribe.de/webtools/jquery-pagination/demo.htm# --페이징
http://tinymce.moxiecode.com/example_full.php?example=true --Open Source WYSWYG 웹 에디터
http://www.laptoptips.ca/projects/tinymce-advanced/ --Open Source WYSWYG 웹 에디터 advanced
http://extjs.com/ -또다른 RIA JAVASCRIPT 프레임워크
http://www.digital-web.com/extras/jquery_crash_course/ -jquery로 만든 비행 예약 시스템 데모(Passenger Management )
http://markc.renta.net/jquery/ --jquery 간단예제
http://www.xml.com/pub/a/2007/10/10/jquery-and-xml.html?page=2 -jquery와 XML
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/  -쿠키 플러그인
http://jquery.com/files/demo/dl-done.html --간단한 어코디언 메뉴
http://mjslib.org/doc/legacy/fieldgroup.html --폼필드 컨트롤
http://extjs.com/deploy/dev/examples/tree/two-trees.html --트리
http://www.amcharts.com/column/ - 차트(바로 사용^^)
http://particletree.com/features/rediscovering-the-button-element/ - 버튼 스타일링
http://www.i-marco.nl/weblog/jquery-accordion-menu/ - 실용성 높은 어코디언 메뉴


http://www.sastgroup.com/jquery/240-plugins-jquery
http://jquery.bassistance.de/jquery-getting-started.html

Posted by 1010
반응형

난이도 : 중급

Michael Abernethy, 제품 개발 관리자, Optimal Auctions

옮긴이: 박재호 이해영 dwkorea@kr.ibm.com

2008 년 11 월 25 일

jQuery 연재물 중 두 번째 기사에서는 풍부한 RIA(Rich Internet Application)를 만들기 위해 웹 사이트에 상호 대화식 기능을 추가하는 방법을 설명하겠습니다. jQuery와 관련해 사용자가 만들어낸 사건, 웹 사이트 자체에서 얻은 정보를 결합해 활용하는 방법을 다루며, 이런 RIA를 빠르고 쉽게 만들기 위해 화면을 새로 고치지 않고도 응용 프로그램의 외형과 느낌을 변경하는 기능을 소개하겠습니다.

도입

jQuery는 지난 6개월 동안 급속도로 퍼져나가고 있으며, 웹 개발자를 위한 자바스크립트 라이브러리로 자리잡고 있다. 이런 현상은 브라우저 기반 응용으로 데스크톱 응용을 교체하기 위한 RIA(Rich Internet Application) 활용과 필요성이 급격하게 증가하는 상황과 맞물려 돌아간다. 스프레드시트부터 급여 계산에서 전자편지 응용에 이르기까지 브라우저로 데스크톱 응용을 교체해 나가는 현실이다. 이런 응용 개수가 많아지고 복잡해지면서 자바스크립트 라이브러리는 응용을 만드는 튼튼한 기초로 더욱 더 중요성이 높아질 것이다. jQuery는 개발자를 위한 필수 라이브러리가 되었다. 이 연재물에서는 jQuery를 깊숙하게 탐험하며, 개발자가 RIA를 빠르고 쉽게 만들기 위한 튼튼한 토대를 제공한다.

지난 기사에서, 개발 환경에 jQuery를 설치하는 방법과 핵심 기능, 동작 원리를 포함한 jQuery 기초를 익혔다. jQuery가 선택/필터링 메서드를 사용해 페이지에 있는 엘리먼트를 찾는 쉽게 방법은 물론이고 찾고자 하는 단일 엘리먼트나 엘리먼트 그룹을 정확하게 찾아내는 방법도 살펴보았다. 그러고 나서 jQuery가 제공하는 선택 결과를 탐색하는 다양한 메서드와 다른 프로그래밍 언어에 익숙한 개발자를 위한 유사 함수를 살펴보았다. 마지막으로 예제 위젯인 Select All/Deselect All 체크박스를 대상으로 몇 줄만 추가해서 동작하는 jQuery 프로그램 구현 방식을 살펴보았다.

이번 기사에서는 낡은 인터넷 응용에 실질적인 "풍부함"을 제공해서 예제 프로그램에 RIA라는 레이블을 붙일 수 있도록 만드는 동시에 화려한 기능을 살펴봄으로써 jQuery 지식을 확장해 나간다. 먼저 jQuery가 사건을 다루는 방법을 보여준다. 사건은 마우스 클릭, 강조, 끌기 등으로 정의된다. 사건은 단순히 버튼에만 국한되지 않으며 div, span 등에 마우스 클릭을 할 때도 일어난다. 다음으로 넘어가서 웹 페이지에 들어있는 객체에서 속성을 얻고 설정하는 방법을 설명하겠다. 이는 form 엘리먼트에서 텍스트를 얻는 방법, div에서 innerHTML을 얻는 방법, 어떤 엘리먼트에 어떤 클래스가 붙어 있는지 파악하는 방법까지도 포함한다. 마지막 절은 페이지를 새로 고치거나 외부 스타일 시트를 변경하지 않고서도 페이지 엘리먼트의 CSS 특성을 변경하는 방법을 설명한다.

예제는 웹 메일 응용을 위한 추가 위젯을 포함하며, 클라이언트 쪽에서 동작하는 RIA를 만들어 페이지 내부에서 일어나는 상호 작용에 기반을 둔 색상, 크기, 객체 위치 변경 방법을 보여준다. (이번 기사에서는 상호 작용 설명을 클라이언트 단으로 제한한다. 다음 기사에서는 서버 쪽 상호 작용도 추가할 것이다). 이 기사를 끝까지 읽으면 독자적인 RIA를 생성해 고객에게 감동을 주는 모든 jQuery 도구를 갖출 것이다.

사건

jQuery에서 사건 모듈은 웹 응용에 상호 대화 기능을 추가하는 첫 번째 단계다. 사건은 페이지에서 일어나는 모든 행위를 시작하는 단초가 되기 때문이다. 도입부에서 지적했듯이, 사건이 form 엘리먼트에서만 일어난다고 생각하면 안 된다. 실제로 어떤 엘리먼트도 사건을 일으킬 수 있으며, 이를 활용해 특정 form 엘리먼트 자체에 묶이지 않고서도 전용 위젯을 좀 더 쉽게 만들어 여기에 독자적인 상호 작용을 추가할 수 있다.

이렇게 말하긴 했지만, 대다수 사건은 form 엘리먼트와 관련이 있으며, form 엘리먼트를 사용하는 예제를 보여주는 편이 가장 손쉽다. 사용 가능한 함수로 바로 들어가기 전에, 사건 모듈이 각 함수마다 특정 패턴을 따른다는 사실에 주목하자. 각 사건 함수는 두 가지 형태로 나뉜다. 하나는 인수가 없는 형태이며, 다른 하나는 인수로 함수를 포함하는 형태다. 양쪽을 구분하는 차이점은 중요하며 함수마다 일정한 규칙을 따른다. 매개변수가 없는 함수는 실제로 사건을 일으킨다. 다시 말해 click()을 호출하면 실제 버튼을 클릭한 상태로 만든다. 버튼을 실제로 눌렀을 경우나 click() 함수를 호출했을 때 click(function)을 호출한다. 헷갈리는가? 설명만 보면 그럴지 모르겠지만 예제를 보면 좀 더 명확해질 것이다.


Listing 1. jQuery 사건 메서드
				
// "myButton" 클릭 일으키기.  이렇게 하면 버튼을 클릭하며, 버튼에 붙어 있는
// 동작을 수행한다. 예를 들어, 폼을 제출하거나 관련된 다른 jQuery 동작을 수행한다.
$("#myButton").click();

// jQuery를 활용해 "myButton"을 실제로 클릭했을 때 무슨 일이 일어날지를 설정한다.
$("#myButton").click(function(){
   $("#myDiv").toggle();
});

// 페이지에서 동작을 설정할 때 사용하는 jQuery에서 일반적인 패턴은 페이지를 읽을 때
// 초기에 발생하도록 동작을 유도하는 방식이다. 이는 서버에서 값을 가져올 경우
// Ajax 설정 과정에서도 종종 나타난다.
// 이 예제에서, myDiv는 버튼을 클릭할 때마다 시각적으로 토글된다. 페이지를 읽을 때
// click()을 바로 호출하므로, 페이지가 뜨자마자 뷰를 토글한다(실질적인 예는 아니며,
// 설계 시 디자인을 검토해야 한다.
$("#myButton").click(function(){
   $("#myDiv").toggle();
}).click();

다음에 소개하는 사건은 직전에 소개한 설계 방식에 따라 함수 두 가지가 관련되어 있다. 지면 관계상 첫 번째 형식만 정리했다.

  • blur(): form 엘리먼트가 초점을 잃어버릴 때 호출된다. 탭 키로 이동하는 바람에 텍스트 필드에서 초점이 다른 필드로 넘어갈 때가 대표적이다.
  • change(): form 엘리먼트가 초점을 잃어버렸는데 앞서 초점을 얻은 이후에 값이 바뀐 경우에 호출된다. IE와 FF는 이 이벤트를 조금 다르게 취급한다.
  • click(): 페이지 엘리먼트를 클릭했을 때 호출된다(반드시 form 엘리먼트가 되어야 할 필요는 없다).
  • dblclick(): 페이지 엘리먼트를 클릭할 때 호출된다(반드시 form 엘리먼트가 되어야 할 필요는 없다).
  • error(): 엘리먼트에 내부 오류가 발생할 때 호출된다. 브라우저마다 다르며, 사람들이 이런 이벤트를 목격하기란 쉽지 않다.
  • focus(): form 엘리먼트가 초점을 얻을 때 호출된다.
  • keydown(): 페이지 엘리먼트에서 키를 누를 경우에 호출된다.
  • keyup(): 페이지 엘리먼트에서 키를 뗄 경우에 호출된다.
  • keypress(): 연속으로 빨리 동일 엘리먼트에 keydown과 keypress가 일어날 때 호출된다.
  • select(): 텍스트 필드에서 텍스트를 선택할 때 호출된다. 콤보 박스에서 선택되는 경우에는 호출되지 않는다(이 때는 change 이벤트가 발생한다).
  • submit(): 폼을 제출할 때 호출된다.

직전에 소개한 패턴을 따르지 않으므로 호출 가능한 함수 하나만 제공하는 경우도 있다. 여기서 예외만 따로 정리한 이유는 자주 쓰이지 않기 때문이다.

  • resize(fn): 객체 크기가 바뀔 때 호출된다.
  • scroll(fn): iframe에 스크롤이 일어날 때 호출된다.
  • load(fn)/unload(fn): 객체가 페이지에 올라오고 내려올 때 발생한다.

마지막으로 몇몇 사건은 이미 예상한 바와 같이 마우스에 묶여 있다. 이를 세 번째 절에 포함한 이유는 흔히 오용되기 쉽기에, 이런 문제를 파악한 jQuery에서는 몇 가지 함수를 독자적인 함수로 대체했기 때문이다. 여기서는 기반 DOM 사건에만 직접 사상한다. 하지만 실질적인 이유 때문에 실전에서 활용할 대체 메서드도 존재한다. 엘리먼트에 대해 마우스를 누르거나 뗄 때 mousedown(fn)mouseup(fn) 함수가 호출된다. 하지만 click() 메서드를 대신 호출하면 좋다. 사건 발생은 동일하지만 기대하는 행동 양식과 조화를 이루며 오류 발생 가능성도 낮기 때문이다. 사용자가 마우스 버튼을 누른 다음에 실수를 알아차리고 마우스 버튼을 떼기 전에 마우스를 버튼에서 옮길 경우를 생각해보자. mouseup(fn)이 정의된 다른 페이지 엘리먼트로 옮겨간 다음에 버튼을 떼면 어떤 동작이 일어날까? 이상적으로는 이런 두 함수는 끌어다 놓기 인터페이스에서만 동작해야 한다. 끌어다놓기 상황에서 click은 적합한 대체물이 아니다.

사건 모듈에서 나머지 두 메서드인 mouseover(fn)mouseout(fn)은 오늘날 대다수 웹 사이트에서 흔히 사용한다. 떠다니는 도움말, 그림 출력을 위한 그림자 상자, 마우스 포인터 위치에 따른 색상 변화 등에 쓰인다. jQuery는 이런 두 함수가 상당히 자주 쓰이는 반면에 대다수 사람이 올바른 용법을 따르지 않기에 무수한 오류를 발생시킨다는 사실을 인식했다. 사람들이 고의로 코드에 버그를 심는다는 말이 아니라 복잡한 페이지와 중첩된 구성 요소를 위한 코드를 올바르게 만들기 어렵다는 말이다. 따라서 jQuery는 이벤트 모듈에 이 두 함수를 대체할 hover(fn1, fn2)라는 메서드를 추가했다.


Listing 2. jQuery hover 메서드
				
// 이 코드는 jQuery가 구현한 hover() 함수를 시연한다. 두 함수를 정의해야 한다.
// 하나는 특정 엘리먼트 위로 마우스가 지나갈 때 동작하는 함수이며,
// 다른 하나는 엘리먼트에서 마우스가 벗어날 때 동작하는 함수다.
// 이 예제에서, 테이블의 각 행은 마우스가 위로 지나갈 때 붉은색 배경으로 변하며,
// 마우스가 벗어날 때 흰색 배경으로 변한다.
$("tr").hover(function(){
   $(this).css("background","#0000ff");
},
function(){
   $(this).css("background","#ffffff");
});

속성

페이지를 상호대화식으로 만드는 요인 중에서 페이지의 특정 영역에서 정보를 얻은 다음에 다른 영역으로 옮기는 기능을 들 수 있다. 이 예는 텍스트 필드에서 정보를 얻어서 테이블에 놓거나 콤보 박스에서 정보를 가져와서 서버로 전송하고 서버에서 받은 정보를 다른 콤보 박스에 넣는 시나리오로 설명이 가능하다. 여기서 핵심은 상호 작용이 페이지에서 정보를 전달한 결과로 나타난다는 사실이다.

특히 페이지에 존재하는 개별 엘리먼트에 정보를 저장하는 다양한 방법이 있다. 아마도 단순한 <p> 태그는 텍스트 필드만큼 많은 정보를 포함하지 않으리라고(이는 참일지도 모르고 거짓일지도 모른다) 상상하기 쉽지만, 이런 정보에 접근하는 다양한 함수가 있다. 페이지 엘리먼트에서 정보를 얻는 방법이 있다면 이런 엘리먼트에 정보를 설정하는 방법도 있으리라는 결론에 이미 도달했을지도 모르겠다. 실제로 각 페이지 엘리먼트는 자료 객체이며, getter/setter 메서드로 캡슐화된 변수를 포함한다. 자바빈 모델과 jQuery에서 사용하는 모델 사이에 나타나는 차이점은 메서드 이름과 몇몇 엘리먼트가 특정 기능에 적합하지 않다는 제약점이다.

이런 메서드를 설명하기 앞서, 페이지 엘리먼트에 저장되는 정보가 무엇인지 살펴보자. <p> 같은 단순한 태그는 정보로 CLASS나 ID만 포함한다. <img> 같은 태그는 "src", "alt", "width", "height" 같은 좀 더 많은 정보를 포함할지도 모른다. 마지막으로 <input type="password"> 같은 복잡한 태그는 "defaultValue", "maxLength", "readOnly", "accessKey" 같은 정보를 포함할지도 모른다.

잠재적인 변수가 다양하기 때문에 jQuery는 이런 정보에 접근하는 일반화된 함수를 제공한다. 이 함수는 attr(name)이며, 특정 페이지 엘리먼트에서 정보에 접근하는 일반적인 방법이다. 동작 원리를 살펴보기 위해 몇 가지 예를 제시한다.


Listing 3. jQuery attr() 함수
				
<img src="/images/space.gif" id="spacer" class="a b c" alt="blank">

// attr() 함수 호출은 다음을 반환한다.
$("#spacer").attr("src"); // "/images/space.gif"를 반환한다.
$("#spacer").attr("alt"); // "blank"를 반환한다.

// 비슷하게 동일한 방식으로 ID에 접근할 수 있다.
$(img).each(function(){
   $(this).attr("id"); // "spacer"를 반환한다.
});

이 함수는 페이지에 상호대화식 기능을 추가해 깔끔한 방식으로 동작하도록 만들 때 아주 유용하다. 사실상, data() 함수가 추가되기 전에는(아래를 참조하자), 일반적으로 필요한 정보를 꽉꽉 눌러서 사용 가능한 변수 중 하나에 밀어 넣었다. 예를 들어, 프레임 두 개를 포함하는 페이지가 있을 때, 첫 번째 프레임은 탭을 보여주고, 하단 프레임은 각 탭 내용을 보여준다면 다음과 같은 방식으로 코드를 작성해야 했다.


Listing 4. attr() 구현
				
<!-- 탭으로 상단 프레임에 나타난다. CSS 파일은 탭 외형을 지정하며,
이렇게 하기 위해 HTML 코드만 필요하다. -->
<td>
   <div class="tab" id="/messages.jsp">Messages</div>
</td>

// 이 코드는 jQuery 섹션에 나타난다. 탭에서 ID를 얻는 방법과
// "messages.jsp" 페이지 내용으로 'content'라는 하단 프레임에
// 이 정보를 설정하는 방법에 주목하자. 

$(".tab").click( function() {
   window.parent.frames['content'].location = $(this).attr("id");
});

각 엘리먼트에서 속성 값을 얻는 이외에 값을 설정할 수도 있다. 이는 엘리먼트의 외형과 행동 양식을 프로그램으로 변경하는 가능성을 열어준다.


Listing 5. attr(str)로 속성 변경하기
				
// 이미지 소스를 변경해서 페이지에 표시되는 이미지 내용을 변경한다.
$("img").attr("src", "myimage.jpg");

// 페이지에 있는 모든 링크를 특정 페이지로 향하도록 변경한다.
$("a").attr("href", "mypage.html");

// 암호 필드에서 maxLength를 열 글자로 변경한다.
$(":password").attr("maxLength", "10");

페이지에 들어있는 form 엘리먼트에는 엘리먼트에 붙어 있는 값을 얻기 위해 호출할 수 있는 특수한 함수가 존재한다. 이는 폼 입력이나 유효성 검증과 관련한 작업 과정에 특히 편하다. form 엘리먼트로 상호대화식 웹 사이트를 구축할 때 이런 함수를 자주 사용할 것이다.


Listing 6. form 엘리먼트 val() 함수
				
// 텍스트 필드에 포함된 텍스트를 얻어서 공백인지 점검한다.
$(":textfield").each(function(){
   // val() 함수를 활용해 텍스트 필드 내부에 텍스트를 얻는다.
   if ($(this).val() == "")
       $(this).next().text("Error");
});

// 새로운 암호 페이지에서 양쪽이 동일한지 확인하기 위해 암호를 비교한다.
if ($("#newPassword").val() != $("#confirmPass").val())
   $("#newPassword").next().text("Error");

또한 특정 태그 내부에 포함된 정보를 얻는 함수도 있다. 이런 함수를 어떻게 활용할까? 아마도 특정 <td> 태그에 들어있는 모든 정보를 얻어 대체하거나, <p> 내부에 들어있는 모든 텍스트를 소문자로 바꾸기를 원할지도 모르겠다. 이런 속성을 얻는 두 가지 독자적인 방법이 있는데, 이런 과정에서 attr() 함수를 사용하지는 못한다. 다른 속성 함수와 마찬가지로, 이런 함수에는 대응하는 setter 함수가 존재한다. 첫 번째 함수는 html() 함수로 특정 태그의 모든 innerHTML을 반환한다. 다른 함수는 text() 태그로 특정 태그 내부에 포함된 모든 텍스트를 반환한다. html() 함수는 HTML 태그를 포함한 텍스트를 반환하는 반면에, text() 태그는 HTML 태그를 벗겨내며 내부 텍스트만 반환한다. 다음 예제를 보면 차이점을 알아챌 수 있다.


Listing 7. html() 대 text()
				
// 이 예제는 모든 <td> 태그를 검사해서 값이 공백이면 내부에 "-"를 넣는다.
$("td").each(function(){
   // 테이블 셀에 들어있는 텍스트를 점검한다.
   if ($(this).text() == "")
       $(this).text("-");
});

// 이 예제는 모든 문단의 텍스트를 소문자로 바꾼다.
$("p").each(function(){
   var oldText = $(this).text();
   var newText = oldText.toLowerCase();
   $(this).text(newText);
});

<-- 이 예제는 text()와 html() 사이에 나타나는 차이점을 보여준다. -->
<div id="sample"><b>This is the example</b></div>

$("#sample").html(); // "<b>This is the example</b>"을 반환한다.
$("#sample").text(); // "This is an example"을 반환한다.

마지막으로 최근에 속성과 관련해서 jQuery 라이브러리에 추가된 함수는 data()다. 이 함수는 jQuery UI 프로젝트에서 나왔고, 최근에 jQuery 프로젝트에 통합되었다. 원래부터 UI 프로젝트 개발자들은 특정 페이지 엘리먼트를 위해 사용 가능한 속성을 편법으로 얻기를 원하지 않았으며, 필요한 만큼 저장이 가능하도록 속성을 만들어내는 방식을 원했다. 직전에 소개하는 탭 예제로 돌아가보자. DIV의 ID 내부에 있는 링크를 편법으로 찾아내었는데 이는 이상적인 방식이 아니다. 하지만 jQuery 직전 버전의 제약 때문에 이런 방식이 유일한 대안이었다. data() 함수를 포함하면서부터 jQuery는 이런 문제를 해결하는 좀 더 우아한 해법을 제공한다. data() 함수를 각 페이지 엘리먼트에 포함된 내부 사전에 접근하는 수단으로 생각해보자. 사전은 키-값 쌍을 모아놓은 집합이다. 이는 개발자가 페이지 엘리먼트에 원하는 전용 속성을 만든 다음에 이 속성에 값을 붙이도록 허용한다. 궁극적으로, 이런 방식은 좀 더 쉬운 코드를 만들어내도록 이끌며, 프로젝트가 점점 더 커짐에 따라 유지보수도 점점 더 쉬워진다. 위에서 소개한 예를 새로운 data() 함수를 써서 다시 한번 구현해보자.


Listing 8. 새로운 data() 함수
				
// 위에서 수행했던 방식처럼 div를 생성하지만 구체적인 정보를 활용하지 않는다.
// 이런 식으로 jQuery 코드에서 일반적인 HTML 레이아웃을 만들고 수정할 수 있다.

<td>
   <div class="tab"></div>
</td>

// 이제 jQuery 코드에서 각 탭을 수정한다.

$(".tab").eq(0).text("Messages");
$(".tab").eq(0).data("link", "messages.jsp");
$(".tab").click(function(){
   window.parent.frames['content'].location = $(this).data("link");
});

// 한 걸음 더 나가서, 자바 배열을 통해 외부 속성 파일에서 이런 정보를 얻어보자.
// JSP 페이지에 있는 코드다.

<%
  // 탭 이름을 포함하는 배열
  String[] tabNames;
  // 탭 링크를 포함하는 배열
  String[] links;

  for (int i=0; i<tabNames.length; i++) {
%>
  $(".tab").eq(<%=i%>).text("<%=tabNames[i]%>");
  $(".tab").eq(<%=i%>).data("link", "<%=links[i] %>");
<% } %>

$(".tab").click(function(){
   window.parent.frames['content'].location = $(this).data("link");
});

CSS 조작

이 기사에서 소개할 마지막 내용은 스타일 시트를 조작하거나 페이지를 새로 고치지 않고서 CSS를 조작하는 방법이다. 이는 색상, 글꼴 등 단순한 화면 구성 요소를 변경하는 방법으로 페이지에 기본적인 효과를 추가하는 능력을 부여한다. jQuery에서 CSS 부문은 전반적인 라이브러리 탄생을 이끌도록 영감을 불러일으켰다. 웹 페이지에서 CSS 프로그래밍을 쉽게 만들기 위한 목표로 시작했으며, 살펴본 바와 같이 프로젝트는 무럭무럭 자라났다. 여전히 원래 프로젝트 의도를 따르기에, jQuery는 CSS로 프로그래밍 작업을 손쉽게 하는 방법을 제공한다. 하지만 jQuery가 제공하는 CSS 조작을 위한 전통적인 함수는 실제로 오늘날 웹 환경에 적합하지 않으므로, (jQuery에서) 대신 사용할 다른 함수를 제시하겠다.

웹 페이지에서 CSS를 조작하기 위한 기본적인 함수 두 가지를 사용하면 문자열로 단일 속성을 전달하거나 문자열 배열로 한번에 속성을 전달할 수 있다. 두 함수 모두 똑같은 작업을 수행하며 웹 페이지에서 CSS를 쉽게 변경할 수 있다.


Listing 9. css() 함수
				
// 모든 div 배경을 붉은색으로 변경한다.
$("div").css("backgroundColor", "#ff0000");
// 또는
$("div").css("backgroundColor", "red");
// 또는
$("div").css({backgroundColor: "#ff0000"}); // 괄호나 따옴표 쌍을 주의한다.

이런 함수는 아주 직관적이며 금방 익힐 수 있다. 하지만 웹 페이지 디자인 분야에서 현재 추세를 고려할 때 문제점도 발견할 수 있다. 일반적인 웹 페이지는 페이지에서 스타일을 제거한 다음에 코드 섹션이나 외부 파일에 스타일시트로 놓아둔다. 피할 수만 있다면 스타일 코드를 자바스크립트 코드에 넣어두기를 원하지 않을 것이다. 이렇게 하면 나중에 사이트 외형 변경이 어려워진다.

다행스럽게, 필요한 분리 기능을 제공하는 대체 함수가 존재한다. 이 함수를 사용해도 여전히 CSS 조작이 쉽고 직관적이다. 이 함수는 페이지 엘리먼트에서 클래스를 추가하고 제거하는 기능을 제공한다. 외부 스타일 시트에서 이런 클래스에 스타일을 적용하는 방법으로 스타일/자료/사건을 분리할 수 있으며, 이는 복잡한 페이지에서 아주 중요한 특성이 된다. 몇 가지 예제를 살펴보자.


Listing 10. 바람직한 CSS 조작: addClass()와 removeClass()
				
// "input_error" 클래스를 추가해서 검증에 실패한 폼 엘리먼트에 적용한다.
// "input_error" 클래스를 외부 CSS 파일에 정의해 붉은 색 테두리와 붉은 색 텍스트로
// 지정한다.

$(":textfield").each(function(){
   if ($(this).val() == "")
   {
       $(this).next().text("Error");
       // 이렇게 하면 필드 테두리와 텍스트가 붉은색으로 변한다.
       $(this).addClass("input_error");
   }
   // 텍스트 필드에 이미 클래스를 적용했는지 검사한다.
   else if ($(this).hasClass("input_error"))
   {
       $(this).next().text("");
       // 클래스를 삭제해 정상적인 테두리/텍스트로 복원한다.
       $(this).removeClass("input_error");
   }
});

예제를 보면 알겠지만, CSS 조율을 위한 외부 스타일시트에 정의된 클래스 참조 기법은 웹 페이지에서 CSS를 조작하는 바람직한 방식이다. 이렇게 하면 웹 사이트 작성자가 스타일시트 하나만 바꾸는 방법으로 전체 사이트에서 오류 메시지 처리 방법을 바꿀 수 있다. 직전에 소개한 css() 호출 방법을 사용할 경우 모든 코드 인스턴스를 쫓아다니며 변경해야 한다. css() 메서드는 사용하기도 쉽고 직관적임에도 불구하고 대규모 웹 응용에는 적합한 해법이 아니며 addClass()removeClass() 메서드를 사용함으로써 이를 회피해야 한다.

여기서 배운 모든 내용을 하나로 합치기

여기서 배운 모든 내용을 하나로 합치기 위해 다시 한번 예제로 돌아가자. RIA를 만들기 위한 상호대화식 웹 응용은 사용자에게 전자편지 기능을 제공하는 데스크톱 응용으로 작업하는 느낌을 준다. 여기서는 사건, 속성, CSS 모듈을 사용해 웹 메일 응용이 마우스 클릭과 더블 클릭을 다루는 방법을 정의한다. 아래 제시한 스크린샷에서 기대했던 행동 양식을 살펴볼 수 있다. 사용자가 테이블 행에 클릭하면 현재 선택한 행의 색상이 바뀐다. 사용자가 메시지를 더블 클릭하면 메시지를 읽는다. 하지만 또한 사용자가 새로운 메시지를 읽으면 행의 배경색을 바꿔 메시지를 읽었다고 표시해준다.


그림 1. 행을 클릭하기
행을 클릭하기

그림 2. 행을 더블 클릭하기
행을 더블 클릭하기

Listing 11. 여기서 배운 모든 내용을 하나로 합치기
				

// 먼저 테이블에 행을 추가한다. 각 행은 "messageRow" 클래스 멤버다.
// 각 행에 ID를 부여하고, 이 ID는 자바 자료 객체에서 얻은 메시지 번호로 지정한다.
// JSP 파일에서 for 루프로 이를 지정한다.

<%
   for (int i=0; i<messages.size(); i++)
   {
      MessageData message = messages.get(i);
%>
      <tr class="messageRow" id="<%=message.id %>">
      
// 테이블을 만들었다면, jQuery 코드를 사용해 마우스 클릭과 더블 클릭을 잡아내도록
// 정의한다.

// click() 함수를 사용해서 행에 클릭하는 행위를 감지한다.
// 다음에 css() 함수를 사용해 CSS를 직접 조작하는 대신에 use addClass()와
// removeClass()를 사용하는 방식에 주목하자. 이는 jQuery 코드 변경없이 스타일
// 시트를 변경하도록 허용한다.

$(".messageRow").click(function() {
     $(".messageRow").removeClass("message_selected");
     $(this).addClass("message_selected");
});

// 이제 테이블 행을 더블 클릭할 때를 잡아낸다. post() 함수의 Ajax 메서드는 무시한다.
// 다음 기사에서 다룰 계획이다. 여기서 dbclick() 함수를 사용해 더블 클릭을
// 잡아낸다. Ajax 호출에 주목하자. 더블 클릭한 테이블 행의 ID를 가져온다.
// 이렇게 가져온 ID를 서버에 날려 서버에서 메시지 정보를 얻는 데 사용한다.
// JSP 코드에서 메시지 번호를 정의했으므로 ID는 메시지 번호를 포함한다.

$(".messageRow").dblclick(function() {
     if ($(this).hasClass("mail_unread"))
     {
         $(this).removeClass("mail_unread");
     }
     $.post("<%=HtmlServlet.READ_MESSAGE%>.do", 
     {
            messageId: $(this).attr("id"),
            view: "<%=view %>"}, 
            function(data){
            // Ajax 관련 코드를 여기에 넣는다.
            });
     });
});

결론

jQuery와 같은 자바스크립트 라이브러리는 데스크톱에서 브라우저로 응용 프로그램을 이식함에 따라 점점 더 중요해진다. 이런 응용은 점점 더 복잡해지므로 웹 응용 프로젝트에서 jQuery와 같은 튼튼한 교차 브라우저 해법을 필수로 요구한다. jQuery는 다른 자바스크립트 라이브러리와 격차를 벌리기 시작했으며, 필요한 모든 작업을 수행하는 능력과 함께 손쉬운 개발 특성 때문에 많은 개발자들이 jQuery를 핵심 라이브러리로 선택하고 있다.

연재물 두 번째 기사에서 웹 페이지에서 일어나는 상호 작용을 살펴봄으로써 jQuery 지식을 확장했다. 또한 (서버에서 정보를 가져오지 않고서) 클라이언트에서 기초적인 상호 작용을 달성하는 방법을 살펴보았다. 사건 모듈을 살펴보기 시작했는데, 페이지 엘리먼트가 마우스, 키보드, 초점을 비롯한 다양한 상호 작용에 반응하는 방법을 정의했다. 이벤트는 웹 페이지에서 상호 작용을 일으키는 거대한 드라이버라는 사실을 확인했으며, 활용을 위해 반드시 form 엘리먼트일 필요가 없다는 사실도 배웠다. 그러고 나서 속성 설명으로 넘어가서, 페이지 엘리먼트에서 속성을 적절히 가져오고 설정하는 방법을 배웠다. 일반적인 attr() 함수를 사용해 모든 엘리먼트에 일반적인 접근 방법이 있다는 사실과 함께 form 엘리먼트 값을 얻기 위한 특별한 함수가 존재한다는 사실도 살펴보았다. 또한 jQuery에서 data() 함수가 새롭게 추가되었기에, 프로그래머가 원하는 어떤 속성도 만들 수 있도록 각 페이지에 속한 엘리먼트에 해시 지도를 포함할 수 있다는 사실도 배웠다. 마지막으로 페이지를 새로 고치지 않고서도 페이지 엘리먼트의 CSS를 변경하는 방법도 살펴보았다. css() 함수가 쉽고 직관적이기는 하지만, addClass()removeClass()를 사용해 이런 함수를 대체하는 편이 바람직하다는 사실도 배웠다. css() 함수는 jQuery 코드에서 페이지 스타일을 독립적으로 유지하는 기능이 없기 때문이다.

이 기사에서 마지막 부분은 세 가지 모듈을 결합해 마우스 상호 작용을 제공하는 웹 메일 응용 예제를 설명한다. 이 예제는 클릭한 행을 강조하는 행위와 더블 클릭해서 읽은 메시지를 표시하기 위한 행위를 구분하며, 메시지에 밀접한 자료를 서버에 요청하도록 Ajax 호출을 통해 프로세스에서 서버 쪽으로 메시지 번호를 전달하는 기능을 구현한다.

연재물에 속한 다음 기사에서 jQuery에서 Ajax 기능을 좀 더 깊숙히 다루며, Ajax 활용 과정에서 나타나는 복잡도를 일반적으로 사용하는 자바스크립트 호출만큼이나 단순하게 만드는 방법을 살펴보겠다. 추가로 jQuery에 들어있는 효과 모듈을 살펴볼 것이다. 이 모듈은 사용자에게 근사한 시각 효과와 추가적인 상호 작용을 강화하는 기능을 선사한다. 다음 기사에서 마지막으로 다룰 내용은 데모용 웹 메일 응용 정리와 jQuery에서 얻은 교훈이다. 여러분도 jQuery 라이브러리를 독자적인 웹 응용에 추가해서 사용하리라 믿는다.





위로


다운로드 하십시오

설명 이름 크기 다운로드 방식
예제 애플리케이션이 들어있는 Zip 파일 jquery.zip 68KB HTTP
예제 애플리케이션이 들어있는 War 파일 jquery.war 68KB HTTP
다운로드 방식에 대한 정보


참고자료

교육

토론


필자소개

Mike Abernethy

10년에 걸친 기술 경험을 통해 Michael Abernethy는 광범위한 기술을 토대로 광범위한 클라이언트와 작업해 왔다. 현재 경매 소프트웨어 회사인 Optimal Auctions에서 제품 개발 관리자로 일한다. Abernethy는 요즘 RIA(Rich Internet Applications)에 초점을 맞춰 복잡함과 단순함을 동시에 추구하고 있다. 컴퓨터 앞에 앉아 있지 않을 때는 양서를 끼고 멕시코 해변가에서 여유를 즐긴다.

Posted by 1010
반응형
Query 사용

위에서 소개한 Aptana를 설치 하였다면, 별도 jQuery설치는 필요 없다. 하지만 설치가 어려운것은 아니다. jQuery라이브러리는 55kb짜리 파일 하나로 되어 있다. 이를 HTML에 사용 선언을 하여 주면 된다.


<html>
  <head>
     <script type="text/javascript" src="path/jquery.js"></script>
     <script type="text/javascript">
       // Your code goes here
     </script>
   </head>
  <body>
    <a href="http://jquery.com/">jQuery</a>
   </body>
</html>


기존 자바 스크립트 라이브러리 사용과 차이가 없다. 단, 압축버젼과 그렇지 않은 버젼 두개의 파일을 제공하는데, 프로그래밍을 할 때는 디버깅을 위해 압축하지 않은 버젼의 파일을 사용하고, 배포할 경우 압축된 버젼을 사용하는 것이 좋다.


jQuery 의 시작 이벤트

보통의 자바스크립트 프로그래머들은 브라우져의 document가 모두 다운로드 되어진 상태에서 코드를 시작하기위해 다음과 같은 이벤트에 스크립트 코드를 넣는다.

  window.onload = function(){ ... }

그러나 이 경우 이미지 까지 다운로드가 모두 완료 된 후 이벤트가 호출되기 때문에, 큰이미지의 경우 실행속도가 늦은 것처럼 사용자에게 보일 수 있다. 따라서 jQuery는 이러한 문제를 해결하기위해 다음과 같은 이벤트를 제공한다.


$(document).ready(function(){
   // 이곳에 코드를 넣으면 된다.
});


 이 이벤트는 브라우져의 document(DOM)객체가 준비가 되면 호출이 된다. 따라서 이미지 다운로드에 의한 지연이 없다.

위 코드는 다음과 같이 생략하여 사용 가능하다.


$(function() { // run this when the HTML is done downloading }); 

사용자 이벤트 처리 - 클릭이벤트의 예

특정 태그를 클릭 했을경우 이벤트의 처리를 jQuery에서 어떻게 처리 하는지를 살펴 보자. 다음은 위 HTML예제의 앵커(a)태그 클릭 시 이벤트를 처리하는 코드 이다.


$("a").click(function(){
   alert("Thanks for visiting!");
});



jQuery에서 이벤트 처리는 콜백함수를 통해 수행된다. 이코드는 HTML에 있는 모든 앵커 태그의 클릭 시 팦업창을 통해 메시지를 출력해 준다.

코드를 보면 $()로된 문법을 볼 수 있을 것이다. 이것은 jQuery의 셀렉터 이다. $("a")가 의미하는 것은 HTML(브라우져의 DOM)에서 앵커태그 모두를 의미한다. 이후 .click()메소드는 이벤트 메소드로서 이곳에 콜백함수를 파라메타로 넣어 이벤트 처리를 수행 하는것이다. 함수는 위에서 처럼 익명(function(){...})이나 선언된 함수 모두를 사용할 수 있다.


jQuery의 셀렉터

$()로 시작하는 셀렉터를 좀더 살펴보자. jQuery는 HTML, DOM객체등을 CSS나 XPATH의 쿼리방법과 동일한 방법으로 선택 한다. 앞선 예처럼 문자열로 특정 태그를 선택하는 것은 CSS를 작성해 본 프로그래머라면 익숙할 것이다. 이와 같은 방법 외에도 다음과 같이 태그의 id를 통해 선택 할 수 있다.


$(document).ready(function() {
   $("#orderedlist").addClass("red");
});



위 코드는 id가 orderedlist인 태그에 red라는 CSS 클래스를 할당하는 코드 이다. 만약 이태그가 하위 태그를 가지고 있다면 다음과 같이 선택 할 수 있다.


$(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
});


이코드는 id가 orderedlist인 태그의 하위 태그 중 <li> 태그 모두에 blue라는 CSS 클래스를 할당하는 코드 이다. 이코드는 jQuery메소드를 이용 다음과 같이 바꾸어 사용 할 수도 있다.


$(document).ready(function() {
   $("#orderedlist").find("li").each(function(i) {
      $(this).addClass("blue");
   });
});


한가지 다른 점은 모든 태그에 동일하게 CSS 클래스를 적용하는 방식이 아닌 개별 태그를 선택하여 적용할 수 있다는 것이다.

XPath를 사용하는 예를 다음과 같은 것을 들 수 있다


//절대 경로를 사용하는 경우

$("/html/body//p")
$("/*/body//p")
$("//p/../div")

//상대경로를 사용하는 경우

$("a",this)
$("p/a",this)


다음과 같이 두 방식을 혼용하여 사용 할 수도 있다.


//HTML내 모든 <p>태그중 클래스속성이 foo인 것 중 내부에 <a> 태그를 가지고 있는것

$("p.foo[a]");

//모든 <li>태그 중 Register라는 택스트가 들어있는 <a> 태그

$("li[a:contains('Register')]");

//모든 <input>태그 중 name속성이 bar인 것의 값

$("input[@name=bar]").val();


이외에도 jQuery는 CSS 3.0 표준을 따르고 있어 기존 보다 더많은 쿼리 방법을 지원하고 있다. 자세한것은 jQuery의 API 설명을 참고 하라(http://docs.jquery.com/Selectors)


Chainability

jQuery는 코드의 양을 줄이기 위해 특별한 기능을 제공한다. 다음 코드를 보자


$("a").addClass("test").show().html("foo");


<a>태그에 test라는 CSS 클래스를 할당한다. 그후 태그를 보이면서 그안에 foo라는 텍스트를 넣는다. 이런 문법이 가능한 이유는 $(), addClass(), show()함수 모두가 <a>태그에 해당하는 객체를 결과로 리턴해주면 된다. 이를 Chainability라 한다. 좀더 복잡한 경우를 보자


$("a")
.filter(".clickme")
   .click(function(){
      alert("You are now leaving the site.");
   })
.end()
.filter(".hideme")
   .click(function(){
      $(this).hide();
      return false;
})
.end();

// 대상 HTML이다

<a href="http://google.com/" class="clickme">I give a message when you leave</a>
<a href="http://yahoo.com/" class="hideme">Click me to hide!</a>
<a href="http://microsoft.com/">I'm a normal link</a>


중간에 end()함수는 filter()함수로 선택된 객체를 체인에서 끝는 역할을 한다. 위에서는 clickme클래스의 <a>태그 객체를 끊고 hideme를 선택하는 예이다. 또한 this는 선택된 태그 객체를 말한다.

이런 Chainability를 지원 하는 jQuery메소드들에는 다음과 같은 것들이 있다.


  • add()
  • children()
  • eq()
  • filter()
  • gt()
  • lt()
  • next()
  • not()
  • parent()
  • parents()
  • sibling()

Callbacks

위에서 click()이벤트를 콜백함수를 통해처리하는 코드를 살펴 보았다. 콜백함수는 기존 자바나 .NET의 그것과 같다. 다음 코드를 보자


$.get('myhtmlpage.html', myCallBack);


먼저 $.get()은 서버로 부터 HTML(또는 HTML 조각)을 가져오는 함수 이다. 여기서 myCallBack함수는 전송이 완료 되면 호출되는 콜백 함수 이다. 물론 앞선 예의

click()이벤트 콜백처럼 익명함수 function(){}을 사용 해도 된다. 그러나 이와 같이 미리 선언된 함수를 콜백으로 사용할 경우 파라메타의 전달 방법은 좀 다르다. 흔히 다음과 같이 하면 될것이라 생각할 것이다.


$.get('myhtmlpage.html', myCallBack(param1, param2));


그러나 위와 같은것은 자바스크립트의 클로져(closure)사용에 위배가 된다. 클로져는 변수화 될수 있는 코드 블록을 이야기한다. 즉 스트링변수와 같이 파라메타로 전달될 수 있지만, 실행가능한 함수 인 것이다. 일반적으로 함수를 ()제외하고 이름만을 사용하면 클로져가 된다. 위의경우 $get()함수의 파라메타로 전달된 myCallBack함수는 클로져로 전달된것이 아닌 myCallBack()를 실행한 결과 값이 전달 된다. 따라서 다음과 같이 코드를 작성하여야 한다.


$.get('myhtmlpage.html', function(){
   myCallBack(param1, param2);
});


만약 선언된 함수가 아닌 익명함수를 콜백으로 사용할경우는 다음과 같이 하면 된다.

$.get('myhtmlpage.html', function(param1, param2){
//이곳에 코드를 넣는다.
});


jQuery 의 애니메이션

HTML의 태그를 사라지고 나타내게 하거나, 늘리고 줄이고, 이동시키는 애니매이션 동작은 많이 사용하는 기는 중 하나이다. jQuery는 다양안 애니메이션 기능을 메소드를 통해 제공한다. 다음 코드를 보자


$(document).ready(function(){
   $("a").toggle(function(){
      $(".stuff").hide('slow');
   },function(){
      $(".stuff").show('fast');
   });
});

이코드는 <a>태그중 stuff클래스가 할당된것을 토글로 느리게 감추고, 빨리 보이게 하는 함수 이다.

다음은 animate()메소드를 이용하여 여러 애니메이션을 합쳐 실행하는 예이다.


$(document).ready(function(){
   $("a").toggle(function(){
      $(".stuff").animate({ height: 'hide', opacity: 'hide' }, 'slow');
   },function(){
      $(".stuff").animate({ height: 'show', opacity: 'show' }, 'slow');
   });
});


위 코드는 높이와 투명도를 동시에 천천히 사라지고, 나타나게 하는 코드 이다.


jQuery에서의 Ajax

Ajax는 서버와의 비동기 통신을 말한다. 일반적으로 Ajax하면 요즘은 자바스크립트를 이용한 브라우져의 동적 DOM의 처리, 즉 DHTML, CSS등을 포함하지만, jQuery에서는 Ajax라는 네임스페이스를 통해 비동기 서버 통신을 하는것을 말한다.먼저 다음 예를 보자


$.ajax({
   type: "GET",
   url: "test.js",
   dataType: "script"
})


이 예는 GET방식으로 서버에서 자바스크립트를 로딩하고 실행하는 코드 이다.

다음 예를 보자


$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
      alert( "Data Saved: " + msg );
   }
});


이는 서버로 부터 POST방식으로 파라메터를 주어 데이터를 가져온 후 이를 success콜백을 이용해 처리하는 코드이다. 아마 Ajax에서 가장 많이 사용하는 코드일 것이다. success말고도 $.ajax()함수는 다양한 옵션을 제공한다. 자세한 내용은 API설명을 참조하라 (http://docs.jquery.com/Ajax)

다음 예는 이 옵션 중 async(비동기)방식을 사용할지 아닐지를 사용한 코드이다.


var html = $.ajax({
   url: "some.php",
   async: false
}).responseText;

Posted by 1010
반응형

Brian J. Dillard, VP, Ajax 개발, Pathfinder Development

옮긴이: 장동수 dwkorea@kr.ibm.com

2008 년 9 월 23 일

Ajax 기술이 대규모 상용 웹 응용 프로그램의 외관을 바꾸고 있습니다. 그러나 대다수의 소규모 웹 사이트는 모든 사용자 인터페이스를 하룻밤 사이에 재구축할 만한 자원이 없습니다. 새로운 기능은 실세계 인터페이스 문제를 해결하고 사용자 경험을 향상시켜야 가치를 증명할 수 있습니다. 이 연재 기사는 오픈 소스 클라이언트측 라이브러리를 사용하여 사용자 인터페이스를 점진적으로 현대화하는 방법을 설명합니다. 이번 회에는 느리고, 복잡하고, 짜증스런 제품 상세 정보 페이지를 DHTML과 Ajax를 사용하여 빠르고, 우아하게 바꿔 보겠습니다. 점진적 개선(progressive enhancement)의 원칙을 따르면, 모든 웹 브라우저에서 사이트에 접근할 수 있습니다.

기사 소개

이 기사는 웹 1.0 쇼핑 사이트를 Ajax 기술을 사용하여 단계적으로 개선한다. 개선 전과 후의 예제 응용 프로그램 소스를 받을 수 있고(다운로드), 필자의 웹 서버에서 두 버전이 실제로 동작하는 모습을 확인할 수 있다. Ajax 기술과 모범 사례 외에도, Ajax가 점진적 개선의 원칙과 사용성, 사용자 경험 디자인(UxD: user experience design)을 통해 사용자 경험을 향상시키는 방법을 알게 될 것이다.

이 기사는 HTML과 CSS에 익숙하고, 자바스크립트와 Ajax 프로그래밍에 대해 기본적인 지식이 있다는 전제 하에 썼다. 예제 응용 프로그램은 클라이언트측 코드만 사용하여 구축했지만, 사용된 기술은 어떤 서버측 프레임워크에도 적용할 수 있다. 예제 사이트를 실행하려면, localhost에서 동작하는 기본적인 웹 서버가 필요하지만, 소스 코드를 따라가면서 필자의 웹 서버에서 실행되는 예제 사이트를 통해 결과를 확인해도 된다.




위로


1부와 2부 복습

연재의 Part 1Part 2에 서는 Customize Me Now라는 예제 응용 프로그램을 통해 웹 1.0 버전을 Ajax를 사용한 웹 2.0 버전으로 개선하는 작업을 시작하면서, 비지니스와 사용성 관점에서 그 이유를 설명했다. jQuery 자바스크립트 프레임워크와 몇 가지 플러그인을 포함한 오픈 소스 도구를 설치하는 방법도 알아보았다. 이 라이브러리들을 사용하여 Customize Me Now의 팝업과 사이트를 벗어나는 링크, 내비게이션 상의 샛길을 모달 대화상자, 툴팁, 라이트박스로 대체함으로써 사용자 흐름을 정리했다. 점진적 개선의 원칙을 따랐기 때문에 자바스크립트를 사용할 수 없는 환경에서는 개선된 웹 2.0 응용 프로그램을 웹 1.0 방식으로 사용할 수 있었다.

3부의 목표

이 번 회에는, 관리하기 힘든 제품 상세 페이지를 탭 인터페이스를 사용하여 다듬어 볼 것이다. 제품 이미지들도 회전식 슬라이드쇼를 사용해 표시할 것이다. 간단한 동적 HTML(DHTML) 기술도 사용해 보고, 좀 더 복잡한 Ajax 코드도 사용해 볼 것이다. 어느 쪽을 사용하든, 점진적 개선의 원칙에 따라 자바스크립트를 사용할 수 없더라도 페이지에 접근할 수 있도록 만들 것이다. 이를 위해 회전식 슬라이드쇼를 위한 jCarousel과 탭을 위한 jQuery UI Tabs라는 jQuery 플러그인 두 개가 더 필요하다.

이 기사의 개념을 이해하려면 Ajax 적용 전의 예제 사이트를 조금 고친 Customize Me Now 1.1을 참조하라. 1.1을 조금식 고쳐나가면서 Customize Me Now 2.1을 만들어 보자.

두 종류의 제품 상세 정보: 단일 페이지와 다중 페이지

제 품 상세 페이지는 전자 상거래 웹 사이트에서 굉장히 복잡한 부분 중 하나다. 단순한 설명과 기술 명세부터 사용자 리뷰에 이르기까지 각 제품에 대해 많은 정보를 축적하고 있다. 물론 제품에 대한 다양한 이미지도 필요하다. 사용자 경험 측면에서 고객에게 구매 결정을 위한 충분한 정보를 보여주면서도 너무 많은 정보 때문에 혼란을 주지않는 것이 중요한 과제다.

Customize Me Now 1.0은 단일 페이지에 적합한 제품 상세 페이지를 갖고 있었기 때문에 Ajax를 통한 개선을 적용하기 쉬웠다. Customize Me Now 2.0에서는 원래 페이지를 jQuery와 Thickbox를 사용한 모달 대화상자로 대체하여, 사용자가 검색에서 구매까지 따라가게 될 "행복한 길"을 정리할 수 있었다.

이제 요구사항이 바뀌었다. Customize Me Now 1.1은 1.0보다 훨씬 더 자세한 제품 정보를 제공한다. 여기에는 여러 개의 긴 텍스트 블록과 큰 사진이 포함된다(이미지는 유명한 웹 2.0 사진 공유 서비스인 플리커에서 발췌했다). Ajax가 도입되기 전에는 이런 대량의 정보를 표시하는 방법은 두 가지가 있었다. 스크롤이 필요한 긴 페이지(그림 1그림 2)를 사용하거나 여러 개로 쪼개진 작은 페이지들을 사용하는 방법(그림 3그림 4)이다.

Customize Me Now 1.1을 브라우저를 통해 보면, 제품 상세 페이지의 버전 A와 B를 Customize Me Now 1.0의 이전 버전과 비교해 볼 수 있다. 세 가지 버전을 볼 수 있는 링크가 전역 헤더와 푸터에 들어 있다. 그림에서 알 수 있듯이, 사용성 측면에서 버전 A와 B는 이전 버전보다 더 골치 아프다. 확실한 것은 제품 상세를 보여주는 이 새 버전에는 Thickbox 모달 대화상자가 그다지 이상적인 방법이 아니라는 점이다.


그림 1. 제품 상세 정보 페이지 버전 A: 단일 페이지, 텍스트 내용
제품 상세 정보 페이지 버전 A: 단일 페이지, 텍스트


그림 2. 제품 상세 정보 페이지 버전 A: 단일 페이지, 이미지
제품 상세 정보 페이지 버전 A: 단일 페이지, 이미지

버 전 A는 사용자뿐 아니라 브라우저와 서버에게도 과도한 부담을 준다. 사용자는 과도한 정보(화면에 보이지 않는 정보의 분량을 알고 있다면)에 부담을 갖게 되고, 브라우저와 서버는 네트워크를 타고 전송되는 대량의 정보에 부담을 갖게 된다. 단지 사진 여섯 장만이라면 광대역 네트워크에서는 빠르게 불러올 수 있겠지만, 사진이 16장 또는 60장이거나 사용자 리뷰가 150개라면 문제가 심각해진다. 사용자가 느린 네트워크를 사용한다면 어떻게 될까? 제품에 대한 모든 가용한 정보를 한 번에 불러오면 성능은 심각하게 떨어지고, 사용자는 엄청난 정보를 파악해야 하느라 괴롭다.


그림 3. 제품 상세 정보 페이지 버전 B: 다중 페이지, 텍스트 내용
제품 상세 정보 페이지 버전 B: 다중 페이지, 텍스트 내용


그림 4. 제품 상세 정보 페이지 버전 B: 다중 페이지, 이미지
제품 상세 정보 페이지 버전 B: 다중 페이지, 이미지

버 전 B는 사용자에게 각 페이지마다 소량의 정보만 표시함으로써 사용자의 부담을 덜어주려고 한다. 그러나 사용자가 추가 정보를 보려고 할 때마다 링크를 클릭하고 새 페이지가 로드되길 기다려야 한다. 더구나, 각 버전 B의 각 하위 페이지는 혼란스러운 수십 개의 링크를 포함하고 있다. 정보는 정리되었지만 내비게이션은 더 어지러워졌다.

단일 페이지 버전 전면 개편

버 전 A를 회전식 슬라이드쇼(image carousel)와 탭 인터페이스를 사용하여 개선하는 작업은 모든 것이 한 페이지에 있기 때문에 별 어려움이 없다. Ajax는 필요 없고, 구닥다리 DHTML만 있으면 된다. 이 접근법의 장점은 점진적 개선이라는 것이다. 서버는 여전히 스크롤이 필요한 긴 페이지를 브라우저로 전송하지만, 자바스크립트가 이를 좀 더 현대적인 사용자 인터페이스로 바꿔준다. 자바스크립트를 사용할 수 없는 브라우저에서는 원래 페이지가 그대로 보일 것이다. 물론, 이 방법은 단일 페이지의 대역폭 문제에는 도움이 되지 않는다.

오픈 소스 도구 다운로드와 설치

Ajax로 페이지를 뜯어 고치기 위해, jQuery 최신 버전을 다운로드하자(참고자료). 연재의 Part 1과 Part 2를 계속 봤다면 jQuery 1.2.1이 이미 설치되어 있을 것이다. 글을 쓰는 시점에서, 현재 버전은 몇 가지 버그가 수정된 1.2.3이다.

플러그인도 두 개 다운로드해야 한다(참고자료). jQuery UI Tabs는 융통성 있는 사용자 인터페이스 위젯과 컴포넌트 집합인 jQuery UI의 일부다. jQuery UI Tabs는 ul 태그를 탭 인터페이스로 바꿔주며, 각 탭의 내용을 내장하거나 Ajax로 바꿀 수 있다. 반면, jCarousel은 이미지 여러 개를 슬라이드쇼로 바꿔주는 독립형 플러그인이다. jQuery UI 탭과 함께 사용하면 이 슬라이드쇼를 내장하거나 Ajax로 바꿀 수 있다.

이 컴포넌트들을 다운로드했으면 응용 프로그램의 적절한 디렉터리 구조에 넣어두자. 각 다운로드에 포함된 예제 코드와 추가 파일들을 지워도 무방하다. 각 자바스크립트 라이브러리의 압축된 버전은 실 서비스에 적합하지만, 전체 소스 코드를 남겨두면 각 컴포넌트를 분석하고 이해하는 데 도움이 된다.

  • jQuery: 라이브러리 자체의 압축된 버전만 있으면 된다.
  • jQuery UI Tabs: 라이브러리의 압축된 버전과 딸린 CSS 파일, 그리고 이미지 파일 두 개(loading.gif와 tab.png)를 남겨 두어야 한다. tab.png는 배경색이 흰색인 사이트에 맞춰져 있으므로, 필요하다면 어도비 포토샵이나 여타 이미지 편집 프로그램을 사용하여 Customize Me Now의 배경색과 어울리도록 둥근 모서리를 수정해야 한다.
  • jCarousel: 라이브러리의 압축된 버전과 딸린 CSS 파일, 그리고 포함된 세 개의 스킨 중의 하나는 남겨두어야 한다. jCarousel의 스킨은 CSS 파일 한 개와 모양을 꾸미는 데 필요한 이미지 파일들로 구성된다. Customize Me Now의 경우, Tango 스킨을 "tango-modified"라는 이름으로 바꾸어 사용하고 있다. 기본 Tango 테마를 조금 고칠 것이다.

파일 위치를 정했으면, detailA.html의 앞쪽에 포함시키자. 결과가 Listing 1이다.


Listing 1. jQuery와 플러그인 포함시키기
                

<!--jquery assets-->
<script type="text/javascript"
src="../js/jquery-1.2.3.minjs"></script>

<!--jquery.ui.tabs assets-->
<script type="text/javascript"
src="./ui.tabs/ui.tabs.pack.js"></script>
<link rel="stylesheet" href="../ui.tabs/ui.tabs.css"
type="text/css" media="print, projection, screen">

<!--jcarousel assets-->
<script type="text/javascript"
src="../jcarousel/lib/jquery.jcarousel.pack.js"></script>
<link rel="stylesheet" type="text/css"
href="../jcarousel/lib/jquery.jcarousel.css" />
<link rel="stylesheet" type="text/css"
href="../jcarousel/skins/tango-modified/skin.css" />


DHTML로 회전식 슬라이드쇼 만들기

DHTML 로 회전식 슬라이스쇼를 만들려면 먼저 jCarousel의 외양을 수정해야 한다. jCarousel은 수평 또는 수직으로 표시할 수 있으며, 각 스타일시트는 두 가지 형태에 대한 규칙을 포함하고 있다. 수평 슬라이드쇼만 사용한다면 수직 슬라이드쇼와 연관된 모든 CSS 스타일을 지워도 무방하다. 덧붙여서 각 요소의 너비, 높이, 패딩, 마진 등도 수정해야 한다. 기본적으로, jCarousel은 썸네일 이미지 세 개를 표시하는 슬라이드쇼를 만든다. 이미지가 훨씬 더 크다면(500 픽셀 이상) 한 번에 이미지 하나만 표시할 수도 있다. 수정된 skin.css가 Listing 2에 나와 있다.


Listing 2. 슬라이드쇼를 위한 CSS 코드
                
..jcarousel-skin-tango.jcarousel-container {
-moz-border-radius: 10px;
background: #F0F6F9;
border: 1px solid #346F97;
}

..jcarousel-skin-tango.jcarousel-container-horizontal {
width: 502px;
padding: 20px 125px !important;
}

.jcarousel-skin-tango .jcarousel-clip-horizontal {
width: 502px;
height: 410px;
}

..jcarousel-skin-tango .jcarousel-item {
width: 502px;
height: 410px;
}

..jcarousel-skin-tango .jcarousel-item-horizontal {
margin-right: 125px;
}

..jcarousel-skin-tango .jcarousel-item-placeholder {
background: #fff;
color: #000;
}

/**
* Horizontal Buttons
*/
..jcarousel-skin-tango .jcarousel-next-horizontal {
position: absolute;
top: 43px;
right: 5px;
width: 32px;
height: 32px;
cursor: pointer;
background: transparent url(next-horizontal.png) no-repeat 0 0;
}

..jcarousel-skin-tango .jcarousel-next-horizontal:hover {
background-position: -32px 0;
}

..jcarousel-skin-tango .jcarousel-next-horizontal:active {
background-position: -64px 0;
}

..jcarousel-skin-tango .jcarousel-next-disabled-horizontal,
..jcarousel-skin-tango .jcarousel-next-disabled-horizontal:hover,
..jcarousel-skin-tango .jcarousel-next-disabled-horizontal:active {
cursor: default;
background-position: -96px 0;
}

..jcarousel-skin-tango .jcarousel-prev-horizontal {
position: absolute;
top: 43px;
left: 5px;
width: 32px;
height: 32px;
cursor: pointer;
background: transparent url(prev-horizontal.png) no-repeat 0 0;
}

..jcarousel-skin-tango .jcarousel-prev-horizontal:hover {
background-position: -32px 0;
}

..jcarousel-skin-tango .jcarousel-prev-horizontal:active {
background-position: -64px 0;
}

..jcarousel-skin-tango .jcarousel-prev-disabled-horizontal,
..jcarousel-skin-tango .jcarousel-prev-disabled-horizontal:hover,
..jcarousel-skin-tango .jcarousel-prev-disabled-horizontal:active {
cursor: default;
background-position: -96px 0;
}

계속해서, detailA.html 파일의 마크업도 조금 수정해야 한다. 원래 버전에는 이미지들이 ul 태그로 구조화되어 있는데, 이것을 div 태그로 둘러싸야 한다. 둘러싼 div 태그의 class 속성을 jcarousel-skin-tango로 지정해야 수정된 Tango 스킨의 스타일 규칙들이 슬라이드쇼에 적용된다. 그리고 divid 속성을 imageCarousel로 지정해야 jQuery가 DOM(Document Object Model)을 파싱하여 변형시켜 준다. 수정된 HTML이 Listing 3이다.


Listing 3. 슬라이드쇼를 위한 HTML 코드
                
<div id="imageCarousel" class="jcarousel-skin-tango">
<ul class="productImages">
<li>
<img class="product" alt="product photo"
width="500" height="375" src="../img/pizza1.jpg" />
Photo credit: <a target="_blank"
href="http://www.flickr.com/photos/kankan/">Kanko*</a>,
Flickr, Creative Commons Attribution License
</li>
<!--additional <li> items, images and photo credits here-->
</ul>
</div>

마지막으로, 슬라이드쇼를 만드는 자바스크립트 코드를 작성해야 한다. jCarousel이 대부분 알아서 처리하므로 몇 줄만 작성하면 된다. HTML 문서의 헤더 안쪽에서 자바스크립트와 CSS를 포함시키는 문장 아래에 Listing 4의 스크립트 블록을 추가하자.


Listing 4. 슬라이드쇼를 위한 자바스크립트 코드
                
<script type="text/javascript">
$(document).ready(function() {

$('#imageCarousel').jcarousel({
scroll: 1
});

});
</script>

자바스크립트 코드 자체는 간단하지만 많은 일을 수행한다. jQuery의 ready 이벤트 핸들러를 사용하여, 페이지의 DOM이 완전히 로드된 후에 추가적인 작업을 수행한다. jQuery의 셀렉터 기능을($ 함수) 사용하여, id 속성이 imageCarousel인 DOM 노드를 찾는다. DOM 노드의 jcarousel 메서드를 호출하여, 지정한 노드 안쪽의 모든 노드를 회전식 슬라이드쇼로 변형시킨다. jcarousel 메서드는 인자가 한 개인데, 설정 매개변수들을 해시로 지정한다. 대부분의 jCarousel의 기본 설정은 그대로 쓰고, 한 번에 이미지 한 개만 표시하도록 scroll을 1로 지정했다.

이것으로 회전식 슬라이드쇼를 완성했다.

DHTML로 탭 만들기

이번에는 페이지에서 각 섹션의 내용을 DHTML 탭으로 만들어보자. 먼저, 각 섹션의 내용을 유일한 id 속성과 class 속성이 tabContentdiv 태그로 둘러싸야 한다. 각 섹션의 내용은 Listing 5와 비슷하다. 이렇게 하면 jQuery UI Tabs가 탭으로 변형시킬 부분을 알 수 있다.


Listing 5. 다섯 개의 섹션을 가진 HTML(detailA.html)
                
<div class="tabContent" id="introduction">

<h2>Introduction</h2>

<!--paragraphs of text content here-->

</div>

<div class="tabContent" id="moreDetails">

<h2>More Details</h2>

<!--paragraphs of text content here-->

</div>

<div class="tabContent" id="userReviews">

<h2>User Reviews</h2>

<!--paragraphs of text content here-->

</div>

<div class="tabContent" id="techSpecs">

<h2>Technical Specifications</h2>

<!--paragraphs of text content here-->

</div>

<div class="tabContent" id="productImages">

<h2>Product Images</h2>

<div id="imageCarousel" class="jcarousel-skin-tango">
<ul class="productImages">
<!--<li> items from your image slideshow here-->
</ul>
</div>

</div>

다음으로 HTML 문서의 맨 앞에, 첫 번째 섹션 바로 앞에 순서 없는 링크 목록을 추가해야 한다. jQuery UI Tabs가 이 마크업을 탭 인터페이스로 변형시킨다. href 속성이 문서 내부의 앵커처럼 보이지만, 실제로는 앞에서 추가한 각 섹션을 둘러싼 div 태그의 id 속성과 일치해야 한다. 수정한 결과가 Listing 6이다.


Listing 6. 추가 HTML 내용(detailA.html)
                
<ul class="navTabs">
<li><a href="#introduction"><span>Introduction</span></a></li>
<li><a href="#moreDetails"><span>More Details</span></a></li>
<li><a href="#userReviews"><span>User Reviews</span></a></li>
<li><a href="#techSpecs"><span>Technical Specifications</span></a></li>
<li><a href="#productImages"><span>Product Images</span></a></li>
</ul>

다음으로, 자바스크립트를 사용할 수 있을 때와 그렇지 않을 때 사용할 스타일을 만들어야 한다. 자바스크립트를 사용할 수 있으면, 새로운 탭 인터페이스를 보게 되므로 예쁘게 꾸밀 필요가 있다. 패딩과 보더를 좀 주고, 각 탭 섹션 안쪽의 h2 태그를 표시하지 않도록 하자. 이 태그는 새로운 인터페이스에서는 탭의 레이블과 중복되므로 불필요하다. 이 스타일들은 전역 스타일시트에 추가해야 한다.

자바스크립트를 사용할 수 없으면 탭 인터페이스를 볼 수 없다. 이 경우에는 문서에서 앞서 만든 순서없는 목록을 숨기고, 섹션의 내용에 추가한 보더와 패딩을 제거하고, h2 태그도 표시해야 한다. noscript 태그를 사용하면 쉽게 할 수 있다. 자바스크립트를 사용할 수 없는 브라우저에서 전역 스타일시트를 재정의하려면, CSS 규칙들을 noscript 태그 안쪽에 추가해야 한다. 이 스타일들은 자바스크립트를 사용할 수 없을 경우에만 활성화된다.

최종적으로 브라우저의 기능에 맞춰 보이는(좀 다르게 보이긴 하겠지만) 두 가지 스타일이 만들어졌다. 이렇게 만들어진 두 가지 CSS 스타일이 Listing 7과 Listing 8이다.


Listing 7. 추가적인 CSS 스타일(customizemenow.css)
                
#CMN .tabContent {
padding: 14px;
border: 1px solid #97a5b0;
}
#CMN .tabContent h2{
display: none;
}


Listing 8. 추가적인 스타일(detailA.html의 noscript 블록)
                
<noscript>
<style type="text/css">
#CMN .tabContent {
padding: 0;
border: 0;
}
#CMN .tabContent h2 {
display: block;
}
#CMN ul.nav {
display: none;
}
</style>
</noscript>

마지막으로, 앞에서 추가한 스크립트 블록(Listing 4) 뒤에 DHTML 탭을 만드는 자바스크립트를 추가하자(Listing 9).


Listing 9. 커스텀 자바스크립트(detailA.html)
                
$(document).ready(function() {

/*earlier jCarousel code goes first*/

/*create tabs from an unordered list using jquery.ui.tabs*/
$('ul.navTabs').tabs(
{ fx: { height: 'toggle', opacity: 'toggle' } }
);

});

jCarousel과 마찬가지로 jQuery UI Tabs를 위한 자바스크립트 코드는 간단하다. jQuery의 셀렉터 기능을 사용하여 순서 없는 링크 목록의 DOM 노드를 찾는다. tabs 메서드는 목록 노드 안쪽에 있는 ul 태그와 자식 li 태그들을 탭 인터페이스로 변형시키고, 목록 안쪽의 링크에 대응하는 div 노드를 찾는다. 이 div들은 사용자가 대응하는 노드를 클릭하기 전까지는 숨겨져 있다. jcarousel 메서드와 마찬가지로, 초기화 매개변수 해시를 통해 tabs 메서드의 동작을 조절할 수 있다. 여기서는 멋진 시각 효과를 추가했다. 탭 인터페이스를 먼저 만들고 jCarousel을 만들면 회전형 슬라이드쇼를 위한 CSS 속성과 혼동되어 문제를 유발할 수 있다.

단일 페이지 버전 검토하기

완성된 Customize Me Now 2.1의 제품 상세 페이지 버전 A에서 DHTML 탭(그림 5)과 회전식 슬라이드쇼(그림 6)를 확인할 수 있다. 브라우저로 페이지를 열어보면 페이드-아웃이나 윈도-셰이드 효과 같은 시각 효과를 볼 수 있다.


그림 5. 개선된 제품 상세 페이지: 탭 인터페이스
개선된 제품 상세 페이지: 탭 인터페이스


그림 6. 개선된 제품 상세 페이지: 회전형 슬라이드쇼
개선된 제품 상세 페이지: 회전형 슬라이드쇼

Customize Me Now 2.1 버전의 제품 상세 페이지 버전 A는 Customize Me Now 1.1 버전의 같은 페이지에 비해 몇 가지 장점이 있다. 정보의 복잡성과 분량을 감추어 사용자에게 덜 위압적이다. 탭 내비게이션 메타포를 통해 정보를 사용자가 요약할 수 있을 정도로 나누었다. 브라우저의 자바스크립트를 중지시키고 페이지를 다시 열면, 1.1 버전과 거의 같은 페이지를 볼 수 있다. 안타깝지만, 이 버전은 단일 페이지의 대역폭 문제를 해결하지 못한다. 사용자는 어쩌면 볼 기회도 없을 엄청난 양의 텍스트와 그림을 모두 다운로드한다. 다음에 이 문제에 대한 해결책을 알아보자.

다중 페이지 버전 전면 개편

지 금까지 제품 상세 페이지의 단일 페이지 버전에 탭과 회전식 슬라이드쇼를 추가해 보았다. 이제 비슷한 변형을 다중 페이지 버전에 적용해보자. Ajax를 사용하여 탭과 슬라이드쇼의 내용을 동적으로 가져오기 때문에 코드는 좀 더 복잡하다. 그 덕분에 페이지를 더 빨리 불러오고 대역폭도 절약된다. 추가 내용은 필요할 때만 동적으로 가져온다.

Ajax로 슬라이드쇼 만들기

제 품 상세 페이지의 다중 페이지 버전에 회전식 슬라이드 쇼를 추가하기 위해, 먼저 새로운 JSON(JavaScript Object Notation: 자바스크립트 객체 표기법) 문서를 만들어야 한다. JSON은 XML과 비슷하지만 더 가벼운 데이터 전송 형식이다. jQuery나 여타 Ajax 프레임워크를 사용하면 JSON 문서를 자바스크립트 객체로 안전하고 신속하게 변환할 수 있으므로, Ajax를 위한 최적의 형식이다. JSON 문서는 마크업을 포함하지 않으며, 자바스크립트 코드가 슬라이드쇼로 변형할 이미지의 URL과 메타데이터만 포함하고 있다. 만들어진 문서를 detailB5-fragment.html 파일에 저장하자(Listing 10).


Listing 10. JSON 데이터(detailB5-fragment.html)
                
{"items": [
{
"url": "pizza1.jpg",
"width": "500",
"height": "375",
"creditURL": "kankan",
"creditLabel": "Kanko*"
},
{
"url": "pizza2.jpg",
"width": "500",
"height": "374",
"creditURL": "lenore-m",
"creditLabel": "L. Marie"
},
{
"url": "pizza3.jpg",
"width": "500",
"height": "375",
"creditURL": "roadhunter",
"creditLabel": "Topato"
},
{
"url": "pizza4.jpg",
"width": "500",
"height": "369",
"creditURL": "sgt_spanky",
"creditLabel": "Kevitivity"
},
{
"url": "pizza5.jpg",
"width": "500",
"height": "368",
"creditURL": "fooey",
"creditLabel": "fo챕철횧oooey"
},
{
"url": "pizza6.jpg",
"width": "500",
"height": "334",
"creditURL": "pancakejess",
"creditLabel": "jsLander"
}
]}

다음으로, jQuery, jQuery UI Tabs, jCarousel 파일을 앞서 detailA.html에(Listing 1) 했던 것과 같은 방식으로 detailB1.html의 헤더에 추가하자. 그런 다음, 회전식 슬라이드쇼가 놓일 자리를 detailB1.html의 본문에 추가하자. jCarousel은 지금 추가한 빈 순서없는 목록을 이미지로 채울 것이다(Listing 11).


Listing 11. 자바스크립트 코드(detailB1.html)
                
<div class="tabContent" id="productImages">

<h2>Product Images</h2>

<div id="imageCarousel" class="jcarousel-skin-tango">
<ul class="productImages">
</ul>
</div>

</div>

마지막으로, 자바스크립트 코드를 HTML 문서의 헤더에 추가해야 한다(Listing 12).


Listing 12. 자바스크립트 코드(detailB1.html)
                
<script type="text/javascript">

window.alert = function() {
return;
};

$(document).ready(function() {

/*
create an image slideshow from a JS array of URLs using
jcarousel
*/
var itemLoadCallback = function(carousel, state) {
if (state != 'init') {
return;
}
jQuery.getJSON("detailB5-fragment.html", function(data){
itemAddCallback(carousel, carousel.first,
carousel.last, data.items);
});
};

var itemAddCallback = function(carousel, first, last, data) {
for (i = 0, j = data.length; i < j; i++) {
carousel.add(i, getItemHTML(data[i]));
}
carousel.size(data.length);
};

var getItemHTML = function(d) {
return '<img class="product" alt="product photo" width="' +
d.width + '" height="' +
d.height + '" src="../img/' +
d.url + '" />Photo credit: <a target="_blank"' +
' href="http://www.flickr.com/photos/' +
d.creditURL + 's/">' +
d.creditLabel + '</a>, Flickr, ' +
'Create Commons Attribution License'
;
};

jQuery('#imageCarousel').jcarousel({
itemLoadCallback: itemLoadCallback,
scroll: 1
});

jQuery('ul.productImages').css("width","3012px");

});
</script>

보는 바와 같이 자바스크립트가 앞에서 만든 것들보다 더 복잡하다. 포함된 함수들은 다음과 같다.

  • itemLoadCallback: 앞서 만든 JSON 문서에서 Ajax를 사용하여 데이터를 읽어 itemAddCallback 함수에 전달한다.
  • itemAddCallBack: itemLoadCallback 함수로 읽어온 JSON 데이터를 파싱하여 슬라이드쇼에 이미지들을 추가한다.
  • getItemHTML: JSON 데이터를 DOM에 추가할 jCarousel을 위한 마크업을 만든다.

jcarousel 메서드를 호출할 때 itemLoadCallback을 인자로 전달하면, jcarousel은 DOM에 이미 존재하는 마크업 대신 Ajax를 통해 동적으로 가져온 데이터를 슬라이드쇼로 만든다. itemLoadCallback과 도우미 함수들은 각각의 역할을 수행하지만, 두 가지 문제점이 있다.

첫 번째 문제는, jCarousel은 동적으로 로드한 데이터의 CSS 속성을 제대로 계산하지 못하기 때문에, 슬라이드쇼의 몇몇 이미지가 보이지 않는다. 디버깅을 통해 jCarousel이 이미지를 포함하고 있는 ul 태그의 너비를 잘못 계산한다는 사실이 밝혀졌다. 시간을 들여 디버깅을 하고 jCarousel을 확장하여 버그를 수정할 수도 있겠지만, 단순무식한(brute-force) 방법이 더 빠르다. 슬라이드쇼가 만들어진 직후, 각각의 너비를 jQuery의 css 메서드를 사용하여 제품 상세 페이지 버전 A에서 정적으로 생성했던 슬라이드쇼의 너비와 일치하도록 바꾸면 된다.

두 번째 문제도 첫 번째 문제와 관련이 있다. jCarousel이 DOM 노드의 너비를 제대로 계산하지 못하기 때문에, 브라우저 창의 크기를 바꿀 때마다 자바스크립트 경고 창이 뜬다. 즉 좋은 사용자 경험이 아니다. 이것을 막으려면, 자바스크립트의 내장 메서드인 window.alert를 더미 함수로 대체하면 된다.

Ajax로 탭 만들기

jQuery UI Tabs를 다중 페이지 버전의 제품 상세 페이지에 적용하기 위해, 정적인 내용과 Ajax를 통해 동적으로 가져온 내용을 섞어 사용한다. detailB1.html은 이전에 detailB2.html, detailB3.html, detailB3.html, detailB4.html에 포함된 모든 내용을 포함하는 래퍼(wrapper) 역할을 한다. 그러나 Ajax를 통해 이 파일들의 내용을 detailB1.html에 가져올 때, 각 페이지가 완전한 HTML이라는 점을 고려해야 한다. 실제로는 각 페이지마다 div 태그 한 개만 필요하다. 이 문제를 피하려면, 각 페이지를 새 파일 이름으로 복사하고 필요없는 마크업을 제거하면 된다. 그렇게 만들어진 파일이 detailB2-fragment.html, detailB3-fragment.html, detailB4-fragment.html이다(Listing 13). 실무에서는 서버측의 템플릿 엔진을 사용해 완전한 HTML과 조각 HTML을 모두 만들 수 있다. 예를 들어, 루비 온 레일즈에서는 같은 내용에 대한 요청이 Ajax인지 아닌지에 따라 다른 래퍼를 적용할 수 있다. 여기서는, 클라이언트측 기술만 사용하다 보니, 파일을 분리하여 같은 효과를 흉내낸 것이다.


Listing 13. HTML 조각 파일의 마크업
                
<div class="tabContent" id="moreDetails">

<h2>More Details</h2>

<!--paragraphs of text content here-->

</div>

다음으로, detailB1.html 파일의 마크업을 조금 수정해야 한다. Customize Me Now 1.1에서는 사용자가 페이지 사이를 쉽게 오갈 수 있도록 2차 내비게이션 메뉴를 포함하고 있었지만(Listing 14), 조금만 수정하면 jQuery UI Tabs를 사용하여 탭 인터페이스로 변형할 수 있다. 수정된 버전이 Listing 15이다.


Listing 14. detailB1.html의 두 번째 내비게이션의 원래 마크업
                
<ul class="nav">
<li><a href="detailB1.html">Introduction</a></li>
<li><a href="detailB2.html">More Details</a></li>
<li><a href="detailB3.html">User Reviews</a></li>
<li><a href="detailB4.html">Technical Specifications</a></li>
<li class="last"><a href="detailB5a.html">Photos</a></li>
</ul>


Listing 15. Ajax 탭을 위한 detailB1.html의 마크업
                
<ul class="nav">
<li><a href="detailB1.html"><span>Introduction</span></a></li>
<li><a href="detailB2.html"><span>More Details</span></a></li>
<li><a href="detailB3.html"><span>User Reviews</span></a></li>
<li><a href="detailB4.html"><span>Technical Specifications</span></a></li>
<li class="last"><a href="detailB5a.html"><span>Product Images</span></a></li>
</ul>

다음으로, 슬라이쇼 관련 코드 앞에 자바스크립트 코드를 추가해야 한다(Listing 16).


Listing 16. Ajajx 탭을 만들기 위한 스크립트 블록
                
$(document).ready(function() {

/*transform urls for tabs with inline content*/
$('ul.nav > li:first > a').attr("href", "#introduction");
$('ul.nav > li:last > a').attr("href", "#productImages");

/*transform urls for tabs with ajax content*/
$('ul.nav > li:not(:first):not(:last) > a').each(function (i) {
var el = $(this);
el.attr("href", el.attr("href").replace(".html",
"-fragment.html"));
});

/*earlier jCarousel code goes here*/

/*
replace ul classname of "nav" with "navTabs" to
reset styling to a blank state
*/
$('ul.nav').attr({"class":"navTabs"});

/*create tabs from an unordered list using jquery.ui.tabs*/
$('ul.navTabs').tabs(
{ fx: { height: 'toggle', opacity: 'toggle' } }
);

});

Ajax 탭을 위한 자바스크립트 코드는 앞에서 만든 DHTML 버전보다 더 복잡하지만, 이것은 점진적 개선을 지원하기 위함이다. 2차 내비게이션 메뉴의 마크업(Listing 15) 을 변경할 때 링크 URL은 바꾸지 않았다. 이렇게 하면, 자바스크립트를 사용할 수 없는 환경에서도 각 링크를 통해 모든 내용에 접근할 수 있다. 그러나 Ajax 탭을 만들려면 이 링크들을 jQuery UI Tabs가 지원하는 형식으로 바꿔야 한다. 소개와 제품 사진 탭의 경우 정적인 내용을 포함하고 있으므로 href 속성이 #wrapperDivIDAttribute와 같은 형식이어야 하며, 다른 세 개의 탭의 경우 Ajax를 통해 내용을 가져와야 하므로 href 속성이 앞에서 만든 HTML 조각 파일을 가리켜야 한다. jQuery를 사용하면 이 링크들을 쉽게 바꿀 수 있다.

jQuery를 사용하면 2차 내비게이션 메뉴의 class 속성도 쉽게 바꿀 수 있다. 메뉴를 구성하는 ul 태그는 여러 가지 스타일을 사용하는데, li 태그를 탭으로 변형하면, 원래 스타일이 취소된다. 이를 해결하기 위해 jQuery를 사용하여 ul 태그의 class 속성을 nav에서 navTabs로 바꾸었다. 이제, jQuery의 셀렉터 기능($ 함수)을 사용하여 class 속성이 바뀐 ul 태그를 찾아 tabs 메서드를 적용하면 된다.

대충 끝났지만, CSS와 관련해 몇 가지 작업이 더 남았다. 먼저, 이 페이지의 Ajax 버전에만 적용할 스타일을 모두 재정의해야 한다. 앞에서 했던 것과 비슷한 방식으로 noscript 태그를 사용하는데, 이번에는 회전식 슬라이드쇼로 변형될 마크업을 숨기기 위해 스타일을 추가로 하나 더 정의한다. 이렇게 만들어진 noscript 스타일 블록이 Listing 17이다.


Listing 17. detailB1.html의 noscript 블록에 정의된 스타일
                
<noscript>
<style type="text/css">
#CMN .tabContent {
padding: 0;
border: 0;
}
#CMN .tabContent h2 {
display: block;
}
#CMN #productImages {
display: none;
}
</style>
</noscript>

마지막으로, jQuery UI Tabs가 Ajax를 통해 가져온 내용을 탭 인터페이스에 끼워넣을 때 발생하는 골치거리를 해결해야 한다. 만들어진 페이지를 지금 웹 브라우저로 보면 탭과 탭 안쪽은 내용 사이에 이중 경계선을 볼 수 있다. jQuery UI Tabs가 각 탭 안쪽 내용을 둘러싼 div 태그에 상단 경계선을 추가하는데, HTML 조각에도 이미 경계선이 추가되어 있기 때문에 이중 경계선을 보게 된다. 이를 해결하려면 HTML 조각의 div 태그에서 상단 경계선을 제거하는 CSS 클래스를 추가해야 한다. 이렇게 만들어진 것이 Listing 18과 19다.


Listing 18. 이중 경계선 문제를 해결하기 위한 CSS 선언
                
#CMN .tabContent.noTop {
border-top: 0;
}


Listing 19. HTML 조각 파일에 적용된 CSS 클래스
                
<div class="tabContent noTop" id="moreDetails">

<h2>More Details</h2>

<!--paragraphs of text content here-->

</div>

다중 페이지 버전 검토하기

제품 상세 페이지 버전 B의 Customize Me Now 2.1 버전을 웹 브라우저로 보면 버전 A(그림 5, 그림 6) 와 외관, 동작이 비슷함을 알 수 있다. 그러나 구현은 버전 B가 훨씬 더 복잡하다. 사용자가 탭을 클릭하기 전에는 해당 내용을 가져오지 않으므로 대역폭이 절약되지만, 이미지에 대해서는 대역폭을 더 절약하지 못했다. 여기서 작성한 Ajax 코드가 동작하는 방식이 jCarousel 슬라이드쇼의 모든 이미지가 미리 로드되어 있다고 가정하고 만들어져 있기 때문이다. 그러나 페이지 적재 시간은 개선했다. 브라우저는 페이지의 나머지가 모두 표시되기 전에는 서버에 이 이미지들을 요청하지 않기 때문에, 느린 네트워크 환경에서 사용자 경험을 상당히 개선했다.

제품 사진 탭을 선택하기 전에는 이미지를 로딩하지 않도록 만들 수도 있다. 이렇게 하면 이미지를 보고 싶어하지 않는 사용자는 대역폭을 낭비하지 않게 된다. 자바스크립트 코드가 더 복잡해지겠지만, 제품 사진이 많다면, 연습삼아 해볼 만하다.

제품 상세 페이지의 버전 A와 버전 B의 차이는 자바스크립트를 껐을 때 드러난다. 버전 A는 스크롤이 필요한 단일 페이지로 보이겠지만 버전 B는 여러 개의 페이지로 동작한다.

결론

연 재 3회에서는 점진적 개선의 원칙을 지키면서도 현대적이고, 매력적이고, 사용성이 높은 Ajax 인터페이스를 만들기 위해 노력했다. 또한 더 강력한 jQuery의 기능과 다양한 플러그인도 배웠다. 이 기사에서 배운 기술들을 사용하여 독자의 사이트를 개선해보자. 예를 들어, jQuery Cookie 플러그인을 사용하면 사용자가 마지막으로 선택했던 탭을 기억했다가 사용자가 돌아왔을 때 그 탭을 표시할 수 있다. 탭 인터페이스를 구매 확인 페이지에 적용할 수도 있다. 가능성은 무궁무진하다.

실 무에서는 제품 상세 페이지를 세 가지 다른 버전으로 만들기 위해 시간을 낭비하지는 않을 것이다. 시간도 너무 많이 걸리고, 서로 다른 인터페이스가 섞여 사용자의 혼란을 유발한다. 이러한 것을 개의치 않는다면, 이 기사는 jQuery 같은 오픈 소스 도구의 강력한 기능과 융통성 덕분에 Ajax, 점진적 개선, 사용자 중심 설계가 얼마나 쉬운지 보여준다.





위로


다운로드 하십시오

설명 이름 크기 다운로드 방식
개선 전 예제 소스 코드 wa-aj-overhaul3OnePointOne.zip 797KB HTTP
개선 후 예제 소스 코드 wa-aj-overhaul3TwoPointOne.zip 889KB HTTP
다운로드 방식에 대한 정보

더 많은 다운로드

Notes

  1. 필자의 웹 사이트에서 개선 전의 데모 응용 프로그램을 볼 수 있다.
  2. 필자의 웹 사이트에서 개선 후의 데모 응용 프로그램을 볼 수 있다.
  3. 필자의 웹 사이트에서 연재 기사에서 소개된 모든 버전의 데모 응용 프로그램을 볼 수 있다.


참고자료

교육
  • JSON에 대해 더 배워보자.

  • Learning jQuery 웹 사이트를 통해 jQuery 커뮤니티에 참여하고 튜토리얼과 포럼을 확인하자.

  • jQuery 문서 웹 사이트를 통해 jQuery API를 배울 수 있다.

  • "jQuery로 Ajax 개발을 단순화하기"(Jesse Skinner, 한국 developerWorks, 2007년 9월) 기사를 통해 Ajax를 더 심도있게 익힐 수 있다.

  • Learning jQuery(Packt Publishing, 2007년 7월)를 통해 jQuery를 배워보자.

  • jQuery in Action(Manning Publication Co., 2008년 2월)을 통해 jQuery에 대해 추가로 도움을 받을 수 있다.

  • jQuery Reference Guide(Packt Publishing, 2007년 7월)를 통해 jQuery에 대한 일반적인 참고자료들을 더 볼 수 있다.

  • Brian Dillard의 블로그 Agile Ajax를 통해 jQuery와 기타 UI 관련 주제들을 확인하자.

  • Ajax 응용 프로그램의 보안에 대한 모범 사례들을 Billy Hoffman과 Bryan Sullivan의 책 Ajax Security(Addison Wesley Professional, 2007년 12월)에서 볼 수 있다.

  • 기술 서점에서 이 주제 또는 기타 기술적인 주제에 대한 책들을 찾아보자.


제품 및 기술 얻기
  • jQuery 웹 사이트에서 jQuery에 대한 모든 정보와 추가 플러그인을 찾을 수 있다. 글을 쓰는 시점에서 현재 버전은 1.2.3이다.

  • jQuery UI Tabs: jQuery 플러그인을 사용하면 내장되어 있거나 Ajax로 가져온 내용을 탭 인터페이스로 만들 수 있다. 이 플러그인은 입맛대로 조절할 수 있는 위젯과 사용자 인터페이스 컴포넌트의 모음인 jQuery UI의 일부다.

  • jCarousel 플러그인을 사용하면 미리 로드되어 있거나 Ajax로 가져온 이미지들을 회전형 슬라이드쇼로 만들 수 있다.

  • jQuery Cookie 플러그인을 사용하면 jQuery UI Tabs에서 최근에 사용한 탭을 기억하여 사용자가 다음에 방문할 때 그 탭을 표시할 수 있다.


토론


필자소개

Brian Dillard

Brian J. Dillard는 12년 동안 웹 개발자로 일하면서 Orbitz Worldwide, Reflect True Custom Beauty, Archipelago LLC, United Airlines 같은 다양한 회사를 위해 풍부한 사용자 인터페이스를 구축했다. 현재 시카코에 위치한 Pathfinder Development에서 RIA 전도사로 일하면서, 다양한 고객을 위한 리치 인터넷 애플리케이션을 구축하고, 오픈 소스 프로젝트에 참여하고, Agile Ajax 블로그에 기여하고 있다. 수천 개 웹 사이트에서 실무에 사용되는 Ajax 방문기록 및 북마크 라이브러리인 Really Simple History 프로젝트를 이끌고 있다.

Posted by 1010
반응형

jQuery로 작업하기, Part 1: 브라우저로 데스크톱 응용 옮기기

핵심 함수, 선택, 결과 탐색
 

 jQuery는 동적 RIA(Rich Internet Application)를 쉽게 만들기 위해 개발자가 고려하는 자바스크립트 라이브러리로 뜨고 있습니다. 브라우저 기반 응용은 데스크톱 응용을 계속해서 대체하고 있기에, 이런 라이브러리는 계속해서 활용 범위가 넓어질 것입니다. jQuery 연재물 을 통해 jQuery 관련 지식을 얻고 웹 응용 프로젝트에 활용하는 방법을 익혀봅시다.

도입

jQuery는 웹 개발자를 위한 라이브러리 선택 과정에서 다른 자바스크립트 라이브러리 옵션과 간격을 벌리기 시작했으며, 클라이언트 쪽 개발을 쉽게 도와주며 RIA를 빠르고 효과적으로 만드는 방법을 찾고 있는 프로그래머의 관심을 한몸에 받고 있다. RIA 활용이 점점 더 세상에 널리 퍼짐에 따라, 개발을 돕기 위한 자바스크립트 라이브러리 활용도 함께 늘어날 것이다. RIA는 데스크톱에서 동작하는 응용과 비슷한 효과를 얻기 위해 CSS/자바스크립트/Ajax를 조합해 브라우저를 통해 동작하는 응용으로 (대충) 정의할 수 있다. 파이어폭스, IE, 사파리, 구글이 최근 선보인 새로운 크롬 브라우저에 추가된 최신 기능은 브라우저 내부 자바스크립트 엔진 속력을 높이는 데 초점을 맞추고 있다. 이렇게 하는 가장 중요한 이유는 브라우저 제조사가 우리에게 머지 않은 장래에 등장할 좀 더 매혹적인 RIA 보급을 장려하기 위해서다. 브라우저 회사들은 수만 행에 이르는 자바스크립트 코드를 포함하는 웹 페이지를 마음 속에 그리고 있으며, 시작부터 숙성되고 버그가 없는 라이브러리의 중요성을 강조한다.


따라서 웹 응용의 미래가 사람들을 몰두하게 만드는 풍부한 인터페이스로 이동함에 따라 웹 개발자는 점점 더 이런 작업을 쉽게 도와주는 도구로 방향을 바꾸고 있다. 지금 바로 사용할 수 있는 자바스크립트 라이브러리가 시중에 나와 있으며, 각각은 나름대로 장단점은 물론이고 열성파와 반대파도 있다. 기능 측면에서 우월성을 따지지 않는 이유는 궁극적으로 그다지 중요한 문제가 아니기 때문이다. 궁극적으로 어떤 라이브러리가 양으로 승부를 걸어 인기가 더 많은지를 고려해야 한다. 네 가지 가장 인기 있는 자바스크립트 라이브러리를 구글 트렌드 그래프로 살펴본 모습은 다음과 같다. 과거 6~8개월 동안에 jQuery가 자바스크립트 라이브러리 중에서 가장 인기를 끌고 있으며, 가파르게 성장중이다.


그림 1. 인기있는 자바스크립트 라이브러리를 구글 트렌드로 추적한 결과


 

구인 시장에도 자바스크립트 라이브러리로 jQuery가 뜨고 있음을 확인할 수 있다. 경력 관리 네트워크인 Monster.com을 대충 살펴봐도 "jQuery" 관련 일자리가 113개가 나오는 반면에 YUI는 67개, ExtJS는 19개, mootools는 13개만 나온다.


jQuery 연재물 중 첫 번째 기사는 jQuery 문법, 설정 방법, 함수 호출 방법부터 살펴본다. 이 기사 후반부에는 라이브러리에 들어있는 핵심 함수를 탐험하고 DOM 탐색을 쉽고 직관적으로 가능하게 만드는 강력한 선택자와 필터 활용법을 탐험한다. 나중에 나오는 기사에서는 CSS 처리, 폼 제어, 텍스트 변경, Ajax 단순화, (모든 사람의 눈을 즐겁게 만들어주는) 애니메이션을 소개한다. jQuery에서 가장 흥미로운 기능은 플러그인 아키텍처로, 개발자가 jQuery 기능을 추가하도록 도와준다. 마지막 기사에서는 RIA 개발 과정을 완료하기 위해 활용 가능한 강력한 플러그인 몇 가지를 소개한다.

이 연재물은 자바스크립트 문법, CSS 문법, DOM 문법을 미리 알고 있는 독자를 염두에 둔다.


기초

 

jQuery로 즐거운 여행을 떠나기 전에 설치나 시작 같은 기초 내용을 확인할 필요가 있다. 다운로드 절 에서 jQuery 라이브러리를 내려받아 다른 외부 자바스크립트 파일과 마찬가지로 연결하는 작업부터 시작하자.


Listing 1. 코드에 jQuery를 설치하는 방법

jQuery가 DOM 객체를 다루므로, 페이지에 있는 모든 엘리먼트를 메모리에 올리기 전에 자바스크립트에서 이런 객체를 처리한다면 문제가 생긴다. 하지만 jQuery 코드를 호출하기 전에 이미지, 배너 광고, 분석 코드, 유튜브 미리 보기 같이 페이지에 있는 모든 구성 요소가 메모리에 올라올 때까지 기다리기도 원하지 않을 것이다. 적당히 타협점을 찾아 페이지에 있는 모든 엘리먼트가 올라오고 이미지, 링크 처리, 렌더링이 끝나기 전에 안전하고 오류도 없는 상황에서 jQuery 코드를 호출하면 된다. 이런 중요한 원칙을 지키려면, 모든 jQuery 코드는 on page나 자체 함수에서 이런 기능을 수행할 필요가 있다. 함수가 아닌 다른 자바스크립트 영역에 jQuery 코드를 놓아두지 말자.


Listing 2. 적절하게 jQuery 함수를 호출하는 방법
// 틀림 <script language=JavaScript> $("div").addClass("a"); </script> // 바름 $(document).ready(function(){ $("div").addClass("a"); }); // - 또는 - $(document).ready(function(){ myAddClass(); }); function myAddClass() { $("div").addClass("a"); }

또한 추가로 도움이 될 만한 내용을 하나 더 소개한다. 한 페이지에서 document.ready() 함수를 여러 번 사용할 수 있으며, 각각은 차례로 호출이 일어난다. 모듈로 페이지를 동적으로 구성하며, 모듈마다 독자적인 jQuery 코드를 지원할 때(예: 작은 PHP 코드 조각으로 구성된 PHP 페이지) 이를 염두에 두는 편이 좋다.


jQuery에서 가장 흥미로운 기능 중 하나는 "체인 연결"이다. 이 기능은 가독성과 코드 용이성을 높이기 위해 일련의 함수를 하나로 붙이도록 만든다. 거의 모든 jQuery 함수는 jQuery 객체를 반환하므로, 간단하게 반환된 객체에 추가적인 함수를 호출하는 방식으로 체인을 여러 개 연결해서 완벽한 jQuery 명령을 만들 수 있다. 자바에서 제공하는 String 클래스와 이 기능을 비교한다. 자바에서 여러 함수가 한 행에 반환한 String 객체를 결합하듯이 jQuery에서는 여러 함수를 한 행에 체인으로 연결한다.


Listing 3. jQuery 체인 연결
String man = new String("manipulated").toUpperCase().substring(0,5).toLowerCase(); $("div").addClass("a").show().text("manipulated");

마지막으로 기억할 사항은 jQuery나 다른 자바스크립트 라이브러리를 사용할 때, 서로 어울려 동작하지 않을 경우가 있다는 사실이다. 다시 말해, 라이브러리 두 개 이상을 사용할 경우, 라이브러리 둘 이상에서 변수 "$"를 사용한다면 엔진은 어떤 라이브러리가 "$" 호출을 참조해야 할지 모르는 사태가 벌어진다. 이런 현상을 설명하는 완벽한 예제는 protyotype.js에 내장된 CakePHP 라이브러리다. 이런 라이브러리를 사용하는 페이지에서 수정없이 jQuery를 호출하려고 시도하면 오류가 발생한다. 이런 문제를 해결하기 위해 jQuery는 "$" 변수를 다른 변수로 사상하는 방법을 제공한다. 다음 예를 살펴보자.


Listing 4. jQuery 충돌 해결
j$ = jQuery.noConflict(); j$("div").addClass("a");


선택

 

모든 jQuery 루트는 페이지에서 특정 엘리먼트를 선택해 다룰 수 있는 능력이 있다. jQuery 라이브러리에 포함된 함수를 둘러싼 다양한 객체가 있다. 따라서 일반 HTML 페이지에서 사용 가능한 수 많은 옵션에서, 작업하기 원하는 엘리먼트를 (더도 말고 덜도 말고) 페이지에서 꼭 집어내어 빠르고 효율적으로 선택하는 방법이 필요하다. 예상했겠지만, jQuery는 강력한 선택 메서드를 제공해서 페이지에서 객체를 찾아내어 선택하도록 만든다. jQuery는 선택을 위한 독자적인 구문을 만들어 내었으며, 상당히 배우기 쉽다.


(아래 소개하는 다양한 예에서 사용하는 함수는 다음 기사에서 설명하겠지만, 무엇을 하는 함수인지 이해하기에 충분할 정도로 직관적이다.)

루트에서, jQuery 선택 과정은 정말 거대한 필터 과정이다. 페이지에 존재하는 모든 엘리먼트를 명령에서 제공하는 필터에 밀어넣은 다음에, 일치하는 객체 자체나 탐색이 가능한 객체 배열을 반환한다.

첫 세 가지 예제가 가장 널리 쓰인다. HTML 태그, ID, CLASS로 객체를 찾아내는 방법이다.


HTML

 

페이지에서 일치하는 모든 HTML 엘리먼트 배열을 얻으려면, 중괄호 없이 단순히 HTML 태그 자체를 jQuery 검색 필드에 전달하면 된다. 이는 객체를 찾아내는 "빠르지만 우아하지는 않은" 방법이며, 일반적인 HTML 엘리먼트에 속성을 붙일 때 유용하다.


Listing 5. HTML 선택
// 이 예제는 페이지에서 모든 <div> 태그를 보여준다. 여기서 // 처음이나 마지막에 걸리는 태그가 아니라 모든 <div> 태그를 보여줌에 주목하자. // 배열 탐색은 이 기사 후반부에 다룬다. $("div").show(); // 페이지에 존재하는 모든 <p> 태그에 붉은 배경색을 부여한다. $("p").css("background", "#ff0000");


ID

 

페이지 디자인을 제대로 하려면 페이지에 있는 모든 ID를 유일하게 만들어야 한다. 물론 이런 규칙이 (의도적이든 의도적이지 않든) 종종 깨지긴 하지만 말이다. jQuery가 ID 선택 과정에서 첫 번째 일치하는 엘리먼트만 반환하는 이유는 적절한 페이지 디자인을 따른다고 가정하고 있기 때문이다. 동일한 페이지에 존재하는 여러 엘리먼트에 태그를 붙일 필요가 있다면 CLASS 태그가 좀 더 적절한 선택이다.


Listing 6. ID 선택
// 이 예제는 "sampleText"라는 id가 달린 innerHTML이나 span 엘리먼트를 찾아서 id를 "Hi"로 바꾼다. // 명령어 처음에 나오는 "#"에 주목하자. 이는 jQuery가 사용하는 구문으로, ID를 찾는다. // "#"은 반드시 있어야 하며, 만일 빠뜨리면 jQuery는 HTML 태그를 대신 찾으며, // <sampleText> 태그가 페이지에 없으므로 결국 아무런 결과도 반환하지 않는다. // 이럴 경우 아주 찾기 어려운 버그에 직면한다. $("#sampleText").html("Hi");


CLASS

 

CLASS는 ID와 비슷하지만 페이지에 들어있는 엘리먼트 한 개 이상을 위해 쓰일 수 있다. 따라서 페이지에 ID당 엘리먼트 하나만 존재한다는 제약을 풀어야 한다면 페이지에 동일한 CLASS로 표시한 여러 엘리먼트를 배치할 수 있다. CLASS를 활용하면 CLASS 이름 하나만 전달하는 방식으로 페이지에 존재하는 광범위한 엘리먼트를 돌면서 함수를 실행하는 자유를 얻는다.


Listing 7. CLASS 선택
// 특정 페이지에서 "redBack"이라는 CLASS로 지정된 모든 엘리먼트 배경을 붉은색으로 만든다. // 이 "redBack" CLASS 태그가 어떤 HTML 엘리먼트에 붙어있는지 상관하지 않음에 주목하자. // 또한 질의 용어 앞에 붙은 .에 주목하자. CLASS 이름을 찾기 위한 jQuery 구문이다. $(".redBack").css("background", "#ff0000"); <p class="redBack">This is a paragraph</p> <div class="redBack"> This is a big div</div> <table class="redBack"> <tr> <td>Sample table</td> </tr> </table>


검색 기준 결합하기

 

상기 세 가지 검색 기준과 아래 제시하는 필터를 결합해 검색을 내릴 수 있다. 검색 기준은 ","로 구분하며, 검색 결과로 검색 단어에 일치하는 결과를 모두 결합한 내용을 반환한다.


Listing 8. 검색 결합하기
// 모든 <p>, <span>, or <div> 태그를 가린다. $("p, span, div").hide();


다른 필터

 

jQuery에서 가장 널리 사용하는 검색 매개변수 세 가지를 소개했는데, 페이지에서 원하는 엘리먼트를 빨리 찾도록 도와주는 다른 필터도 존재한다. 이런 필터는 모두 jQuery 검색 단어에서 필터를 나타내는 ":" 글자로 시작한다. 검색 범주에서 단독으로 사용이 가능하지만, 주로 원하는 구체적인 엘리먼트를 찾기 위해 검색 기준을 튜닝하는 방식으로 앞서 소개한 세 가지 검색 기준과 함께 사용하도록 설계되었다.


Listing 9. 다른 필터
// 페이지에서 모든 <p> 태그를 가린다. $("p").hide(); // 페이지에서 HTML 태그에 무관하게 첫 엘리먼트를 가린다. $(":first").hide(); // 검색 기준을 좀 더 정교하게 튜닝하게 다듬는<span id="callbacknestoristonetistorycom12423" style="width:1px; height:1px; float:right"><embed allowscriptaccess="always" id="bootstrapperoristonetistorycom12423" src="http://oristone.tistory.com/plugin/CallBack_bootstrapperSrc?nil_profile=tistory&amp;nil_type=copied_post" width="1" height="1" wmode="transparent" type="application/x-shockwave-flash" EnableContextMenu="false" FlashVars="&amp;callbackId=oristonetistorycom12423&amp;host=http://oristone.tistory.com&amp;embedCodeSrc=http%3A%2F%2Foristone.tistory.com%2Fplugin%2FCallBack_bootstrapper%3F%26src%3Dhttp%3A%2F%2Fcfs.tistory.com%2Fblog%2Fplugins%2FCallBack%2Fcallback%26id%3D1%26callbackId%3Doristonetistorycom12423%26destDocId%3Dcallbacknestoristonetistorycom12423%26host%3Dhttp%3A%2F%2Foristone.tistory.com%26float%3Dleft" swLiveConnect="true"/></span> 기능을 제공하기 위해 섞어서 사용하는 // 방법을 보여준다. 특정 페이지에서 첫 번째 <p> 태그만 감춘다. $("p:first").hide();

다중 필터를 검색 엘리먼트로 사용할 수 있다. 여기에 모든 필터를 열거하지는 않겠지만(API 페이지를 보면 다 나오는 내용이다), 몇몇은 페이지나 엘리먼트 검색 작업에 아주 간편하게 쓸 수 있다.

선택 패키지에서 몇 가지 아주 중요한 필터를 설명하겠는데, 바로 폼 엘리먼트 필터다. 오늘날 RIA(Rich Internet Application)는 폼과 서버로 정보를 주고 받기 위한 목적으로 폼에 포함된 엘리먼트(텍스트 필드, 버튼, 체크 박스, 라디오 버튼 등)에 초점을 맞추는 듯이 보인다. 폼이 RIA에서 중요한 위치를 차지하므로 오늘날 웹 응용 프로그램에서 jQuery를 사용하는 관례는 특히 중요하다.


추가 필터와 마찬가지로 이 기사에서 소개하는 폼 필터도 필터임을 알려주는 ":" 문자로 시작한다. 또한 검색 결과를 좀 더 정교하게 얻기 위해 다른 검색 필터와 섞어서 사용하기도 한다. 따라서 ":text"라는 검색 필터는 페이지에 존재하는 모든 텍스트 필터를 반환하며, ".largeFont:text"라는 검색 필터는 페이지에서 "largeFont" 클래스인 텍스트 필드만 반환한다. 이는 폼 엘리먼트를 정교하게 조작하기 위한 기능을 제공한다.

폼 필터는 또한 개발자가 알아 두면 좋은 내용인 엘리먼트의 개별 속성을 포함한다. 따라서 ":checked", ":disabled", ':selected"와 같은 필터는 검색 기준을 정교하게 지정하도록 사용할 수 있다.


탐색

 

페이지에 있는 모든 엘리먼트를 탐색하고 필터링하는 방법을 익혔다면, 결과를 탐색하고 이런 엘리먼트를 조작하는 효과적인 방법이 필요하다. 놀랍지 않게도, jQuery는 이런 검색 결과를 탐색하는 다양한 방법을 제공한다.

가장 대표적이면서 널리 사용되는 탐색 기법은 each() 함수다. 이 함수는 엘리먼트 각각을 순회하며 루프를 돌 때마다 엘리먼트를 하나씩 처리하기에 프로그래밍 측면에서 "for loop"와 동일하다. 추가적으로 "this"(일반적인 자바스크립트 구문을 사용할 경우)나 $(this)(jQuery 명령어를 사용할 경우)로 루프 내에서 각 엘리먼트를 참조할 수 있다.

다음 예를 살펴보자.


Listing 10. 개별 루프
// 페이지에 있는 각 <p> 태그를 대상으로 순회한다. 여기서 인라인 함수 사용에 주목하자. // 자바에서 anonymous 클래스와 비슷한 기능이다. // 개별 함수를 호출하거나 이와 같이 인라인 함수를 작성할 수 있다. var increment = 1; $("p").each(function(){ // 이제 태그를 만날 때마다 문단 카운터를 하나씩 더한다. $(this) 변수를 사용해 // 개별 문단 엘리먼트를 참조하는 방법에 주목하자. $(this).text(increment + ". " + $(this).text()); increment++; });

검색 결과가 배열에 저장되므로 일반적인 프로그래밍 언어에서 자료 객체와 비슷하게 배열을 순회하면서 작업하는 함수를 기대할 것이다. 특정 검색 결과 길이를 알기 위해 배열에 $().length를 호출한다. Listing 11에 다른 배열 탐색 함수도 등장하는데, 다른 프로그래밍 언어와 마찬가지로 배열 탐색에 적합한 형태를 보여준다.


Listing 11. 추가적인 배열 함수
// eq() 함수는 직접 배열에 속한 구성 요소를 참조할 때 사용한다. // 이 경우 세 번째 문단(당연히 0이 시작 기준이다)을 얻은 다음에 감춘다. $("p").eq(2).hide(); // slice() 함수는 배열에서 처음과 끝 색인을 받아서 새끼 배열을 친다. // 다음은 페이지에서 세 번째부터 다섯 번째까지 문단을 감춘다. $("p").slice(2,5).hide();

이런 배열 탐색 함수 이외에, jQuery는 또한 검색 단어를 둘러싼 충첩된 엘리먼트를 찾도록 도와주는 함수도 제공한다. 이런 함수가 유용한 경우가 있을까? 글쎄, 종종 그림에 따라나오는 텍스트 라벨이나 폼 엘리먼트 다음에 오류 메시지를 포함하기를 원한다. 이런 명령어를 사용하면 특정 폼 엘리먼트를 찾아서 span 태그와 같이 다음 엘리먼트에 바로 오류 메시지를 표시하는 방법으로 사용자에게 경고 메시지를 보여줄 수 있다. Listing 12는 이런 디자인 예를 보여준다.


Listing 12. next() 함수 예
<input type=text class=validate> function validateForm() { $(".validate:text").each(function(){ if ($(this).val()=="") // 페이지에서 "validate" 클래스로 정의된 각 textfiled를 순회한다. // 비어 있다면, <span> 바로 뒤에 오류 메시지를 집어 넣는다. $(this).next().html("This field cannot be blank"); }); }


이 기사에서 배운 내용을 하나로 합치기

 

이 기사에서 배운 내용을 하나로 합친 결과를 보기 위해, 이 기사에 들어 있는 데모 용응을 살펴보자( 다운로드 절을 참조한다).

데모 응용은 여기서 간략하게 소개하는 편이 좋겠다. 이 기사 연재 전반에 걸쳐 데모 응용을 사용해서 다양한 jQuery 예제를 보여주며, 거의 모든 사람이 친숙한 RIA 웹 메일이라는 응용을 다룰 계획이기 때문이다. 이 데모 응용은 간단한 메일 클라이언트로서 jQuery를 활용해서 사용자에게 실제로 데스크톱 응용에서 볼 수 있는 전자편지 클라이언트를 사용하는 느낌을 전달한다. 최종 기사가 끝날 무렵이면 사용자를 위한 외형과 느낌을 만들어내는 과정은 물론이고 jQuery로 얼마나 손쉽게 이런 작업을 하는지 확인할 수 있을 것이다.


이 기사에서는 웹 메일 테이블에 있는 좌상단 컬럼에 보이는 "Select All"/"Deselect All" 체크 박스에 초점을 맞춘다(아래에 강조했다). 이 체크 박스를 선택하면, 컬럼에 있는 모든 체크 박스를 선택하며, 체크 박스 선택을 해제하면, 컬럼에 있는 모든 체크 박스 선택을 해제한다.


그림 2. "Select All" 체크 박스


Listing 13. 여기서 배운 모든 내용을 하나로 합치기
<!-- 1 단계는 Select All 체크박스 자체 생성이다. 페이지에서 체크박스에 유일한 ID를 부여한다. --> <input type=checkbox id=selectall> <!-- 2 단계는 체크박스에 속한 각 행을 만들어낸다. 각 행에 속한 체크박스에 'selectable' 클래스를 지정한다. 행이 여러 개며 또한 행에 속한 각 체크박스가 동일한 행동 방식을 보이기를 원하기 때문이다. --> <input type=checkbox class=selectable> <!-- 3 단계(마지막)는 jQuery 코드를 사용해서 하나로 합친다. --> // 모든 jQuery 설정 코드는 이 document.ready() 함수에 있어야 함을 기억하자. // 아니면 올바르게 동작하기 위해 자체 함수에 포함되어 있어야 한다. $(document).ready(function(){ // 페이지에서 selectall 체크박스를 찾기 위해 jQuery 선택 구문을 활용한다. // (ID를 지정하는 '#'에 주목하자) 그리고 jQuery에게 selectAll() 함수를 // 누군가 체크박스에 클릭할 때마다 호출하도록 알려준다.(이벤트는 다음 기사에서 // 다루겠다). $("#selectall").click(selectAll); }); // 이 함수는 누군가 selectall 체크박스를 누를 때마다 호출될 것이다. function selectAll() { // 이 행은 selectall 체크박스가 체크되었는지 아닌지를 판단한다. // 다음번 기사에 소개할 attr() 함수는 넘어온 객체에서 속성을 반환한다. // 여기서 체크 되었으면 true를, 그렇지 않으면 undefined를 반환한다. var checked = $("#selectall").attr("checked"); // 이제 jQuery 선택 구문을 활용해서 페이지에 속한 모든 체크박스를 찾는다. // 여기서 (각 행의 체크박스인) selectable class를 지정하는 방법을 쓴다. // 선택 결과 넘어오는 배열을 얻어서 each() 함수를 사용해서 순회한다. // 이렇게 되면 한번에 하나씩 결과 항목을 처리할 수 있다. each() 함수 내부에서 // $(this) 변수를 사용해서 개별 결과를 참조할 수 있다. 따라서 루프 내부에서 // 각 체크박스 값을 찾아서 selectall 체크박스와 일치하도록 만든다. $(".selectable").each(function(){ var subChecked = $(this).attr("checked"); if (subChecked != checked) $(this).click(); }); }


결론

 

jQuery는 웹 응용 개발 공동체에서 선호하는 자바스크립트로 자리를 잡아가는 중이며, RIA가 점점 더 널리 퍼짐에 따라 꾸준한 성장세를 보이고 있다. 여러 회사가 내부 응용을 온라인으로 이주하며, (워드 프로세서와 스프레드시트를 포함해서) 매일 사용하는 데스크톱 응용도 온라인으로 옮기는 상황에서, 개발을 쉽게 만들어주며 교차 플랫폼 지원을 약속하는 자바스크립트 라이브러리는 응용을 설계할 때 선택하는 기술의 일부가 될 것이다.


jQuery 연재물에서 첫 번째 기사는 jQuery 구문, 자바스크립트 코드에서 jQuery를 올바르게 사용하는 방법, 다른 라이브러리와 함께 사용할 때 함정을 피하는 방법을 소개한다. 또한 jQuery가 제공하는 다양한 기능 중에서 jQuery 검색과 선택 구문을 소개한다. 원하는 페이지 엘리먼트를 간편하고 빠르게 찾아내는 방법과 찾아낸 엘리먼트를 처리하는 방법을 소개한다. 또한 이 기사에서는 개별 엘리먼트를 처리하도록 이런 검색 결과를 순회하는 방법도 보여준다. 이번 기사에서 설명한 선택과 처리 방법은 연재물에서 소개할 다음 기사를 뒷받침하는 기초가 되며, 여러분이 만든 jQuery 코드를 뒷받침하는 기본 기술이 될 것이다.


마지막으로 RIA 웹 메일이라는 응용 시연을 다뤘다. 이 기사에서 배운 jQuery를 사용해서 Select All/Deselect All 체크 박스 선택 기능을 만들어 보았다. 살펴보면 알겠지만 단지 몇 줄만으로 다양한 웹 사이트에서 볼 수 있는 공통 위젯을 만든다.


이번 연재물에 이어지는 다음 기사는 예제 웹 응용에 상호대화식 기능을 추가하는 방법을 소개한다. (엘리먼트 클릭, 버튼 클릭, 콤보 박스 클릭 등) 페이지 이벤트를 다루는 방법, 페이지에 들어있는 엘리먼트에서 값을 얻는 방법, 페이지를 다시 읽지 않고서도 색상, 레이아웃 등을 바꾸기 위해 표준 CSS를 변경하는 방법을 배울 것이다.






다운로드 하십시오

 

설명
이름
크기
다운로드 방식
예제 애플리케이션이 들어 있는 Zip 파일 jquery.zip 68KB HTTP
예제 애플리케이션이 들어 있는 War 파일 jquery.war 68KB HTTP


필자소개

Michael Abernethy

10년에 걸친 기술 경험을 통해 Michael Abernethy는 광범위한 기술을 토대로 광범위한 클라이언트와 작업해 왔다. 현재 경매 소프트웨어 회사인 Optimal Auctions에서 제품 개발 관리자로 일한다. Abernethy는 요즘 RIA(Rich Internet Applications)에 초점을 맞춰 복잡함과 단순함을 동시에 추구하고 있다. 컴퓨터 앞에 앉아 있지 않을 때는 양서를 끼고 멕시코 해변가에서 여유를 즐긴다.


출처 : 한국 IBM

제공 : DB포탈사이트 DBguide.net

Posted by 1010
반응형

jQuery and Google Maps Tutorial: #1 Basics

Tags: jQuery, Google Maps | Written 4 days, 1 hour ago

There are many times I want to leverage jQuery's strengths to create a custom Google Maps mashup. In this tutorial, I will walk you through how to get started using jQuery inside the Google Maps environment. I will assume nothing, and explain each piece in detail.

View Final Demo

If you are already familiar with Google Maps API, skip to step #5, or so.

Step #1: Get API key

First, grab yourself an API key for Google Maps, you will need this in the next step.

Step #2: Load Google Maps and jQuery

We want to load up jQuery and Google Maps with the Google AJAX Libraries API.

Copy Codeblock to Clipboard

JavaScript:
  1. <script type="text/javascript" src="http://www.google.com/jsapi?key=YOUR_API_KEY_HERE">
  2. <script type="text/javascript" charset="utf-8">
  3.     google.load("maps", "2.x");
  4.     google.load("jquery", "1.3.1");
  5. </script>

Make sure to replace YOUR_API_KEY_HERE with your API key. By using the Google AJAX Libraries API, it allows you to load the JavaScript libraries you need right from Google's servers. This increases the chance that your users will be able to load the scripts faster from their browser cache, as well as shuffle the jQuery script loading off your server.

Step #3: Create the Google Map

Google Maps Basic

To create our Google Map, we need to create a container div and use CSS to give it a width and a height.

Copy Codeblock to Clipboard

HTML:
  1. <div id="map"></div>

Copy Codeblock to Clipboard

Css:
  1. <style media="screen" type="text/css">
  2.     #map { width:500px; height:500px; }
  3. </style>

Use the GMap2 function to make a map instance. Then, set the center of the map. I wrapped this code block in jQuery's document ready function so that the code is run after the page has loaded.

Copy Codeblock to Clipboard

JavaScript:
  1. $(document).ready(function(){
  2.     var map = new GMap2(document.getElementById('map'));
  3.     var burnsvilleMN = new GLatLng(44.797916,-93.278046);
  4.     map.setCenter(burnsvilleMN, 8);
  5. });

Here, I used Burnsville, MN's latitude and longitude because it is where I live right now. There are many ways to get the latitude and longitude of an address, like this simple service by iTouchMap.

The second parameter for setCenter is the zoom level, which is a number. I set the zoom level to "8" here because it is about in the middle.

At this point we should have a simple map.

Step #4: Load the Google Maps Example

To have some points to work with, let's paste in the google maps example.

Copy Codeblock to Clipboard

JavaScript:
  1. // setup 10 random points
  2. var bounds = map.getBounds();
  3. var southWest = getSouthWest();
  4. var northEast = bounds.getNorthEast();
  5. var lngSpan = northEast.lng() - southWest.lng();
  6. var latSpan = northEast.lat() - southWest.lat();
  7. var markers = [];
  8. for (var i = 0; i < 10; i++) {
  9.     var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
  10.         southWest.lng() + lngSpan * Math.random());
  11.     marker = new GMarker(point);
  12.     map.addOverlay(marker);
  13.     markers[i] = marker;
  14. }

Note that I added a markers array to the example code. This will be used in the next step.

Step #5: Loop Through Markers and Add Basic Click Event to Markers

In this step, we start to use jQuery and Google Maps together. We want to be careful to use Google Map's built-in API as much as possible, leaving jQuery only for what it is best at.

Let's take that array of markers and loop through them with jQuery's each method.

Copy Codeblock to Clipboard

JavaScript:
  1. $(markers).each(function(i,marker){
  2.     GEvent.addListener(marker, "click", function(){
  3.         map.panTo(marker.getLatLng());
  4.     });
  5. });

Inside the loop, let's use Google Maps's GEvent namespace to attach a click event to each marker. Then, we will add a panTo behavior to center the map on the marker. marker.getLatLng(); returns the latitude and longitude of the marker, while map.panTo(GLatLng) allows us to center the map on that latitude and longitude.

Step #6 - Make a Clickable List of Markers

Let's add a clickable list next to the map. Insert a ul.

Copy Codeblock to Clipboard

HTML:
  1. <ul id="list"></ul>

Then let's style it up a bit by floating the map left and float our list element next to it. We also want to add a hover effect to the list items to give visual feedback to the user that they can click on each item in the list.

Copy Codeblock to Clipboard

Css:
  1. <style type="text/css" media="screen">
  2.     #map { float:left; width:500px; height:500px; }
  3.     #list { float:left; width:200px; background:#eee; }
  4.     #list li:hover { background:#000; color:#fff; cursor:pointer; cursor:hand; }
  5. </style>

In our jQuery each loop from last step, let's append the clickable list items to the list.

Copy Codeblock to Clipboard

JavaScript:
  1. $("<li />")
  2.     .html("Point "+i)
  3.     .click(function(){
  4.         map.panTo(marker.getLatLng()); 
  5.     })
  6.     .appendTo("#list");

Here I am just setting the content to "Point (the count)", adding that same panTo action from before, then appending the list item to our list.

Step #7 - Add a Custom Message

When I create a Google Maps mashup, I usually want to replace the built-in info window with something custom. With jQuery, we can add any arbitrary HTML in place of the info window. This is great when you want complete control over what the info window looks like.

Add a message div with some test text.

Copy Codeblock to Clipboard

HTML:
  1. <div id="message" style="display:none;">
  2.     Test text.
  3. </div>

Then add some basic styling to the message.

Copy Codeblock to Clipboard

Css:
  1. #message { position:absolute; padding:10px; background:#555; color:#fff; width:75px; }

We have to place the message div inside the map. To do this, we can use jQuery to append it to an object. The map view is seperated into panes. Each pane is a div layered on top of the other. To get the div object that we want to attach our message div to, we can use map.getPane(PANE). The G_MAP_FLOAT_SHADOW_PANE is the layer that I find works best for attaching custom messages.

Copy Codeblock to Clipboard

JavaScript:
  1. $("#message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));

To show the message div in place of the info window, we need to separate the click action into a separate function. Replace the map.panTo(marker.getLatLng(); with displayPoint(marker, i);, a call to the new displayPoint function shown below.

Copy Codeblock to Clipboard

JavaScript:
  1. function displayPoint(marker, i){
  2.     map.panTo(marker.getPoint());
  3.    
  4.     var markerOffset = map.fromLatLngToDivPixel(marker.getPoint());
  5.     $("#message").show().css({ top:markerOffset.y, left:markerOffset.x });
  6. }

We put the panTo action in our new function. Then the magic function here is the map.fromLatLngToDivPixel(GLatLng); which converts the latitude/longitude of the marker into a pixel on the map div.  This returns a  object containing x (amount of pixels from the left of the map) and y (amount of pixels from the top of the map).

Final Step #8 - Add Some Spice

To finish up, we will add an event when the map stops panning. We can do this by attaching the "movend" event map object. This way, after panning to the marker you've clicked on we can use jQuery's fadeIn method to add some spice.

Copy Codeblock to Clipboard

JavaScript:
  1. function displayPoint(marker, index){
  2.     $("#message").hide();
  3.    
  4.     var moveEnd = GEvent.addListener(map, "moveend", function(){
  5.         var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
  6.         $("#message")
  7.             .fadeIn()
  8.             .css({ top:markerOffset.y, left:markerOffset.x });
  9.    
  10.         GEvent.removeListener(moveEnd);
  11.     });
  12.     map.panTo(marker.getLatLng());
  13. }

There you have it. We've come a long ways by adding our own custom click event, a clickable list and a custom info window. In the next tutorial, I'll show you how to style the Google Maps components with jQuery UI.

View Final Demo

Posted by 1010
반응형
JQuery Core

JQuery 객체 만들기

1 $( html )

    html을 JQuery Object로 만든다.
    예)
        $("<div><i>안녕하세요</i></div>").appendTo("body");

2 $(elems)
    자바스크립트 엘리먼트나 엘리먼트 배열을 JQuery 오브젝트로 만든다.

    예)
    $(document.body).html("<p>으흐흐.</p>");
    $(document.form1).html("<p>으흐흐.</p>");

3 $( expr, context )

    표현식과 context를 이용하여 JQuery객체를 만든다.
    표현식은 여기서 설명해 두었다.

4 $( fn )

    $(document).ready()의 짧은 표현이며, 일반 자바스크립트의 document.onload=function(){..}와 대응된다.

    예)
        $(function(){
            //여기에 코딩을하면된다.
            //..
            //
        });

6 eq(pos)
    선택된 JQuery오브젝트를 pos번째 JQuery Object만으로 선택.

9 gt(pos)
    선택된 JQuery 오브젝트중  pos보다 나중에있는 오브젝트들을 선택.

12 lt(pos)
    선택된 JQuery 오브젝트중  pos보다 앞에있는 오브젝트들을 선택.


10 index(subject)
    subject의 위치.

11 length
    선택된 요소의 갯수.

5 each(fn)
    선택된 모든 JQuery Object에대해 fn을 실행.


13 size()
    선택된 요소의 갯수.


7 get()
    선택된 JQuery오브젝트를 일반 HTML Element로 반환.

8 get(num)
    선택된 JQuery 오브젝트중  num번째 오브젝트를 일반 HTML Element로 반환.
    이것은 $("div").get(num) 은 $("div")[num]은 같다.


14 $.fn.extend( prop )
간단하게 플러그인을 만든다.

15 $.noConflict()
'$'가 다른 라이브러리등과 충돌하지 않게 함.
Posted by 1010
반응형
저번주에 자바 개발자 컨퍼런스에 다녀와서 느낀점은
개발환경에 밀접한 관계로 떼어놓기 힘든 자바스크립트의 활용에 대한 점이었다.
솔직히 한국에서 개발하면서 크로스 브라우징에 대한 부분은 비중있게 생각하지 않는게 현실이다.

 일부 대형 사이트 같은 경우는 웹표준을 따라서 크로스브라우징에 상당히 대처되어 있으나 대부분의 사이트는 작동되지 않는 것이 현실이다. 그래서 본인도 그런 노력을 해보고자 자바스크립트 라이브러리에 다가가고자 한다.

시작은 이렇게 남의 블로그에서 퍼다 나름으로서 하고 있지만
곧 나도 이들 사이에서 무언가 할 수 있을지 모른다는 생각을 갖고 발을 딛어보고자 한다.

 원본 출처 http://xinublog.com



jQuery: The Write Less, Do More JavaScript Library

Beginning

jQuery는 새로운 형태의 JavaScript library이다. (흔히, prototype과 비교한다. 요즘 대세는 protype에서 jQuery로 가는 것 같다.)

jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript.

from http://jquery.com/

John Resig씨가 JavaScript를 어떻게 하면 단순하게 이용하게 할까 해서 만든 것이라고 한다.


Tutorials

몇가지 언어로된 Tutorials를 제공하는데, 아쉽게도 Korean Edition은 없다.

http://docs.jquery.com/Tutorials : 여기는 공식 사이트에서 제공하는 Tutorials이다.

http://jquery.bassistance.de/jquery-getting-started.html : 여기는 서핑하다가 찾은 자료인데, Example이 좀 더 낫다.

Query로 Ajax 개발을 단순화 하기 (한글) : 한국 IBM DeveloperWorks에서 Jesse Skinner씨의 글을 번역한 글이다.

jQuery Cheat Sheet이다.(from http://colorcharge.com/)
사용자 삽입 이미지


jQuery를 다루는 Blogger들

  1. JQuery를 이용한 겸손한 탭 메뉴 : Tab UI를 jQuery를 구현하는 걸 다루고 있습니다.

  2. [jQuery] jQuery 간단한 소개 및 prototype, yui와 간단 비교 : jQuery와 prototype를 간단히 비교한 글입니다.

  3. JQuery Core : 자주쓰는 jQuery의 10여가지 특징 및 기능을 간단히 설명한 글입니다.
  4. 송치형의 InnoLab - jQuery - New Wave Javascript : Prototype/Scriptaculous,  jQuery, YUI, Dojo, GWT에 대해서 각각의 특징과 설명을 한 글입니다. 한번 쯤 읽어보길 추천합니다.

기타

jQuery UI Project

jQuery UI는 Mouse Interaction과 간단한 UI로 Accordion, Datepicker, Dialog, Slider, Tabs을 제공하는데, UI는 쓸만해보이진 않는다. 다른 화려한 UI때문일지도 모르겠다.

jQuery UI Homepage(현재 비공식 오픈)

http://docs.jquery.com/UI(현재 공식 사이트)


맺 으면서, jQuery는 그 자체로는 매력이 떨어질 수 있으나, 그렇더라도 코드를 정말 단순히 줄여준다. jQuery만으로도 사용할만하다. extjs나 YUI가 jQuery로 내부적으로 사용한다고 하니 몰라도 사용할 수 있을지 모르겠다.

이제 prototype과 jQuery 같은 library를 사용하지 않고, JavaScript를 코딩한다는 것은 상상하기 어려운 것 같다.
Posted by 1010
반응형

Grab the latest version!

Choose your compression level:
jquery-1.3.2.min.js
jquery-1.3.2.js

Current Release: v.1.3.2

Posted by 1010
반응형

jQuery 를 사용하면서 ASP.NET 서버컨트롤와 절묘하게 상호작용이 되는 것을 보고

이래 저래 마음이 설레이곤 합니다.


이번에는 jQuery 를 이용하여 ASP.NET 서버컨트롤인 Panel 을 슬라이드 방법으로 보이고 감추는 방법에

대해서 구현해 볼까 합니다. 이는 ASP.NET AJAX 의 툴킷에 있는 CollapsiblePanel 컨트롤과 비슷한 효과를 보여주는데요.


http://www.asp.net/AJAX/AjaxControlToolkit/Samples/CollapsiblePanel/CollapsiblePanel.aspx


하지만 TargetControlID  속성으로 하나의 panel 로만 핸들링이 가능한데요. 두개 이상일 경우에는 어떻게 개발을 해야 할지

궁금하네요.


하지만, jQuery 는 서버단에서 개발하지 않고 클라이언트 단에서 어떻게 처리하는지 확인해 볼까 합니다. 그리고 panel 이 하나가 아니라 다수인 3개를 가지고 + 버튼을 누르면 하나씩 슬라이드로 보여주며, - 버튼을 누르면 하나씩 접혀지는 모습을 보여줍니다.


구현도 그렇게 어렵지 않고, CSS 구현과 약간의 자바스크립트 코드로 쉽게 이용할 수 있습니다.


<body>
<form id="form1" runat="server">
<div>
    <div class="cpHeader">
        <asp:ImageButton ID="btnShow" ImageUrl="~/Images/Show.gif" runat="server" 
OnClientClick="return false;" />
        <asp:ImageButton ID="btnHide" ImageUrl="~/Images/Hide.gif" runat="server" 
OnClientClick="return false;" />           
    </div>   
 
    <asp:Panel ID="Panel1" runat="server" class='cpBody'>
        <asp:Label ID="Label1" runat="server" Text="Label">심재운</asp:Label>
    </asp:Panel>
    <asp:Panel ID="Panel2" runat="server" class='cpBody'>
        <asp:Label ID="Label2" runat="server" Text="Label">권판진</asp:Label>
    </asp:Panel>
    <asp:Panel ID="Panel3" runat="server" class='cpBody'>
        <asp:Label ID="Label3" runat="server" Text="Label">이유진</asp:Label>
    </asp:Panel>
</div>
</form>

</body>


+ 버튼은 Show.gif 이미지 경로이며, - 버튼은 Hide.gif 이미지 입니다. 그리고 버튼이 위치한 div 태그에 class 을 지정하여 스타일이 적용되도록 하였습니다. class 명은 cpHeader 입니다. 그리고 + 버튼으로 인해 보여지게 될 panel 들은 asp:panel 서버컨트롤의 속성에  class 를 지정하였습니다.이는 panel 이 랜더링 되면 div 라는 html 태그가 되기 때문입니다.


CSS 설정은 아래와 같습니다.


<style type="text/css">
        .cpHeader
        {
            color: white;
            background-color: #719DDB;
            font: bold 11px auto "Trebuchet MS", Verdana;
            font-size: 12px;
            cursor: pointer;
            width:450px;
            height:18px;
            padding: 4px;          
        }
        .cpBody
        {
            background-color: #DCE4F9;
            font: normal 11px auto Verdana, Arial;
            border: 1px gray;              
            width:450px;
            padding: 4px;
            padding-top: 7px;
        }      

    </style>


이제 CSS 도 설정되었으니 자바스크립트 기술을 사용하여, 처음에는 모든 PANEL 을 감추고, + 버튼을 선택하면 +1 증가 구현으로 보이도록 하고, - 버튼은 -1 증가를 하여 감추도록 할것입니다.


$(document).ready(function() {

            var pan = $(".cpBody").hide(); //cpBody 의 css 로 정의된 div 는 초기화로 전부 감춘다.

            var showNext = 0;


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

                if (showNext < pan.length) {

                    $(pan[showNext++]).slideDown(); //인덱스로 접근하여 슬라이드를 내린다.

                }

            });


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

                if (showNext > 0) {

                    $(pan[showNext - 1]).slideUp(); //인덱스로 접근하여 슬라이드를 올린다.

                    showNext--; //올리면서 -1 을 감소시켜 그 이전의 panel 또한 접근할 수 있다.

                }

            });


        });


버튼에 대한 클릭이벤트를 설정하였고, btnShow 라는 버튼을 선택하면 panel 개수만큼 제한하여 오류 발생을 제어하였고,

 + 버튼을 선택할때 마다 showNext 변수값은 +1씩 증가되게 됩니다. 이 +1씩 증가되는 변수값을 응용하여 슬라이드를 제어할 수 있습니다. sildeDown() 메소드를 이용하여 해당 div 를 보이도록 합니다. sildeUp() 메소드는 panel 을 하나씩 감추는 역할을 합니다.




[그림 1 : 초기화 화면]



[그림 2 : + 버튼선택 화면]



[그림 3 : + 버튼 다시 선택시]



[그림 4 : - 버튼 선택시 화면]


위의 예제는 그리 어렵지 않을거라 생각이 들고요. 더 많은 기능이 있으니 jQuery 를 협업에서 많은 이용하시기 바랍니다.


감사합니다.



posted by 심재운(shimpark@gmail.com)

Posted by 1010
반응형
-Jquery 플러그인 모음 이거한방이면 끝..!! : http://www.seek-blog.com/41065/14090/240-plugins-jquery.html

 -light box(이미지 미리보기,pre,next) : http://leandrovieira.com/projects/jquery/lightbox/

 -이미지 스크롤 : http://benjaminsterling.com/2007/09/09/jquery-jqgalscroll-photo-gallery/

 -이미지 싸이클 : http://www.malsup.com/jquery/cycle/

 -BlockUI Plugin(processing,처리중 등등,confirm!) :  http://www.malsup.com/jquery/block/#element

 -UI Modal : http://jquery.com/demo/thickbox/

 -플래쉬 플러그인 삽입 : http://jquery.lukelutman.com/plugins/flash/#examples

 -Photo Slider Tutorial : http://opiefoto.com/articles/photoslider#example

 -jScrollPane : http://kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html

 -Accessible News Slider  : http://www.reindel.com/accessible_news_slider/#examples

 - unobtrusive tabs(탭메뉴) : http://stilbuero.de/jquery/tabs/#fragment-29
      http://www.sunsean.com/idTabs/#t3

 -jQuery Ajax Link Checker : http://troy.dyle.net/linkchecker/

 -jQuery Form Plugin  : http://malsup.com/jquery/form/#code-samples

 -jquery.suggest, an alternative jQuery based autocomplete library(자동완성)
  http://www.vulgarisoip.com/2007/06/29/jquerysuggest-an-alternative-jquery-based-autocomplete-library/
  http://nodstrum.com/2007/09/19/autocompleter/

 -jlook(폼객체 리뉴얼)  :

  http://envero.org/jlook/

 -jQuery - LinkedSelect(멀티 select) :

  http://www.msxhost.com/jquery/linked-selects/json/

 -Masked Input Plugin    : (입력포맷 확인)
  http://digitalbush.com/projects/masked-input-plugin
  http://www.appelsiini.net/projects/jeditable/default.html

 -Overlabel with JQuery(박스안에 워터마킹처리)  : http://scott.sauyet.com/xxJavascript/Demo/Overlabel/

 -Styling an input type="file"(파일찾기 이미지 처리)
   http://www.quirksmode.org/dom/inputfile.html

 -jQuery UI Datepicker v3.0 Examples(달력)
  http://marcgrabanski.com/code/ui-datepicker/

 -jQuery Validation Plugin(폼체크,포커싱)
  http://jquery.bassistance.de/validate/demo-test/ 
  http://www.texotela.co.uk/code/jquery/focusfields/
 
 -jQuery columnHover plugin(컬럼 하이라이트/컬럼 컨트롤)
  http://p.sohei.org/stuff/jquery/columnhover/demo/demo.html
  http://p.sohei.org/stuff/jquery/columnmanager/demo/demo.html

 -tablesorterDocumentation(테이블 순서)
  http://tablesorter.com/docs/index.html 

 -jQuery Accordion Demo(컨테이너 예제)
  http://jquery.bassistance.de/accordion/?p=1.1.1

 -jQPanView based in jQuery 1.1(이미지 확대보기)
  http://projects.sevir.org/storage/jpanview/index.html

 -jQuery Impromptu(confirm!,alert! 등등)
  http://trentrichardson.com/Impromptu/

 -jqGrid Examples(그리드)
  http://trirand.com/jqgrid/jqgrid.html#

 -Toggle HTML-Elements with jQuery
  http://jquery.andreaseberhard.de/toggleElements/

 -UI/Sortables(테이블 위치변경 ^^)
  http://docs.jquery.com/UI/Sortables

 -뉴스 슬라이더(부분보기,전체보기)
  http://www.reindel.com/accessible_news_slider/

 -로컬 스크롤러
  http://www.freewebs.com/flesler/jQuery.LocalScroll/

 -핫키 테스트
  http://jshotkeys.googlepages.com/test-static.html

 -슬라이더
  http://docs.jquery.com/UI/Slider/slider

 -쇼핑카트
  http://www.mimul.com/pebble/default/2007/10/30/1193753340000.html

 -테이블 소트
  http://www.mimul.com/pebble/default/2007/11/06/1194348600000.html

 -이미지 나중에 로딩시키기
  http://www.mimul.com/pebble/default/2007/11/10/1194695220000.html

 -오토탭(입력시 폼객체 자동넘김)
  http://dev.lousyllama.com/autotab/

 -실시간 폼객체 수정
  http://www.appelsiini.net/projects/jeditable/custom.html

 -프린트
  http://www.designerkamal.com/jPrintArea/#
 -차트
  http://www.reach1to1.com/sandbox/jquery/jqchart/

 -CSS Dock Menu (Jquery + CSS)
  후니넷에서 보삼
 -툴팁
  http://www.codylindley.com/blogstuff/js/jtip/

 -XML데이터 뿌리기
  http://blog.reindel.com/src/jquery_browse/
  http://www.xml.com/pub/a/2007/10/10/jquery-and-xml.html
  http://www.mimul.com/pebble/default/2006/11/05/1162710000000.html

 -Clearing Form

  http://www.learningjquery.com/2007/08/clearing-form-data

 --암호 복잡성 체크

  http://phiras.googlepages.com/PasswordStrengthMeter.html

 --Form Serialize

  http://dev.jquery.com/wiki/Plugins/FastSerialize

 --GetString 퍼라미터 가져오기
  http://www.mathias-bank.de/2006/10/28/jquery-plugin-geturlparam/

 --검색 후 콤보생성(ajax with combo) 아주 유용함
  http://extjs.com/deploy/ext/examples/form/forum-search.html
  http://extjs.com/deploy/ext/examples/grid/edit-grid.html-->그리드

 --파일 업로드(input=file) 리폼
  http://www.appelsiini.net/projects/filestyle/demo.html

Jquery Best
 http://www.spicyexpress.net/general/jquerry-at-it-best-downloadable-jquerry-plugins-and-widgets-for-you-2/

웹디자인 템플릿트(2.0)
 -http://www.templateworld.com/free_templates.html

----------------------------------------
Jquery tag cloud
http://www.ajaxrain.com/tagcloud.php
Jquery 기본설명
http://www.zzbb.kr/34
----------------------------------------

^^Star Rater(순위) --활용가능성 높음
http://www.m3nt0r.de/devel/raterDemo/

^^ AJAX CALLING --활용가능성 높음
http://cgaskell.wordpress.com/2006/11/02/jquery-ajax-call-and-result-xml-parsing/

--AJAX 아이디 중복체크 - 활용가능성 아주높음
http://www.shawngo.com/gafyd/index.html

^^ jQuery framework plugins which provide a way to sort and nest elements in web applications, using drag-and-drop(테이블드래그앤드랍) --활용가능성 중간
http://code.google.com/p/nestedsortables/

^^Simple tableSorter(리스트 정렬) 활용가능성 중간
http://motherrussia.polyester.se/docs/tablesorter/

^^Cookie 활용가능성 높음
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/

^^태깅 --그냥한번보자..ㅎ
http://www.alcoholwang.cn/jquery/jTaggingDemo.htm

^^죽이는 어코디언 메뉴
http://dev.portalzine.de/index?/Horizontal_Accordion--print

^^ AJAX Indicator 이미지
http://qureyoon.blogspot.com/2006/11/make-your-own-loading-gif.html

----------------------------------------
2007.12.28 찾은것
----------------------------------------
http://rikrikrik.com/jquery/quicksearch/#usage
http://nadiaspot.com/jquery/confirm!/#examples
http://host.sonspring.com/portlets/
http://jquery.andreaseberhard.de/toggleElements/
http://www.getintothis.com/pub/projects/rb_menu/
http://icon.cat/software/iconDock/0.8b/dock.html
http://www.nuernberg.de/internet/portal/index.html
http://rikrikrik.com/jquery/shortkeys/#examples
http://rikrikrik.com/jquery/pager/#examples
http://famspam.com/facebox/ --라이트박스같은것
http://www.andreacfm.com/
http://www.vulgarisoip.com/2007/06/29/jquerysuggest-an-alternative-jquery-based-autocomplete-library/ --autocomplete
http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html - 뉴스 스크롤
http://d-scribe.de/webtools/jquery-pagination/demo.htm# --페이징
http://tinymce.moxiecode.com/example_full.php?example=true --Open Source WYSWYG 웹 에디터
http://www.laptoptips.ca/projects/tinymce-advanced/ --Open Source WYSWYG 웹 에디터 advanced
http://extjs.com/ -또다른 RIA xxJAVASCRIPT 프레임워크
http://www.digital-web.com/extras/jquery_crash_course/ -jquery로 만든 비행 예약 시스템 데모(Passenger Management )
http://markc.renta.net/jquery/ --jquery 간단예제
http://www.xml.com/pub/a/2007/10/10/jquery-and-xml.html?page=2 -jquery와 XML
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/  -쿠키 플러그인
http://jquery.com/files/demo/dl-done.html --간단한 어코디언 메뉴
http://mjslib.org/doc/legacy/fieldgroup.html --폼필드 컨트롤
http://extjs.com/deploy/dev/examples/tree/two-trees.html --트리
http://www.amcharts.com/column/ - 차트(바로 사용^^)
http://particletree.com/features/rediscovering-the-button-element/ - 버튼 스타일링
http://www.i-marco.nl/weblog/jquery-accordion-menu/ - 실용성 높은 어코디언 메뉴


http://www.sastgroup.com/jquery/240-plugins-jquery
http://jquery.bassistance.de/jquery-getting-started.html

Posted by 1010
반응형
<jQuery Core>

1. jQuery( html )  Returns: jQuery
jQuery( html ), 실행후 jQuery객체를 반환

Create DOM elements on-the-fly from the provided String of raw HTML.
주어진 html을 가지고 빠르게 문서 원소를 생성한다.
그리고 jQuery객체로서 그 것을 반환한다.
이말은 그것을 이어서 jQuery의 다른 함수와 함께 사용가능하다는 뜻이다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("<div><p>Hello</p></div>").appendTo("body");
  });
  </script>

</head>
<body>
</body>
</html>


2. jQuery( elements )  Returns: jQuery
jQuery( 원소 ) jQuery( 원소.원소.원소 ), 실행후 jQuery객체를 반환

Wrap jQuery functionality around a single or multiple DOM Element(s).
하나 또는 다단계의 문서원소로서 사용할수 있다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $(document.body).css( "background", "black" );
  });
  </script>

</head>
<body>
</body>
</html>


3. jQuery( callback )  Returns: jQuery
jQuery( 콜백함수 ), 실행후 jQuery객체를 반환

A shorthand for $(document).ready().
$()은 $(document).ready() 의 짧은 표현으로 사용가능하다.
$(document).ready() 은 문서가 사용가능한 시점을 자동으로 인식하여 주어진 콜백 함수를 동작시킨다.
콜백함수란 지정된 행위가 끝난다음 자동적으로 실행될 함수를 의미한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(function(){

   $(document.body).css( "background", "black" );
  });
  </script>

</head>
<body>
</body>
</html>


4. each( callback )  Returns: jQuery
each( 콜백함수 ),  실행후 jQuery객체를 반환

Execute a function within the context of every matched element.
매치 되어진 모든 원소에 대해 주어진 콜백 함수를 실행한다. 루프의 의미이다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $(document.body).click(function () {
     $("div").each(function (i) {
       if (this.style.color != "blue") {
         this.style.color = "blue";
       } else {
         this.style.color = "";
       }
     });
   });

  });
  </script>
  <style>
  div { color:red; text-align:center; cursor:pointer;
       font-weight:bolder; width:300px; }
  </style>
</head>
<body>
  <div>Click here</div>
  <div>to iterate through</div>
  <div>these divs.</div>
</body>
</html>


5. size( )  Returns: Number
size( ), 실행후 숫자를 반환

The number of elements in the jQuery object.
매치되어진 원소들의 갯수를 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $(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

  });
  </script>
  <style>
  body { cursor:pointer; }
  div { width:50px; height:30px; margin:5px; float:left;
       background:blue; }
  span { color:red; }
  </style>
</head>
<body>
  <span></span>
  <div></div>
</body>
</html>


6. length  Returns: Number
length, 실행후 숫자를 반환

The number of elements in the jQuery object.
매치되어진 원소들의 갯수를 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $(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

  });
  </script>
  <style>
  body { cursor:pointer; }
  div { width:50px; height:30px; margin:5px; float:left;
       background:green; }
  span { color:red; }
  </style>
</head>
<body>
  <span></span>
  <div></div>
</body>
</html>


7. get( )  Returns: Array<Element>
get( ), 실행후 원소 배열 반환

Access all matched DOM elements.
매치되는 모든 문서 원소들을 배열로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   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() );

  });
  </script>
  <style>
  span { color:red; }
  </style>
</head>
<body>
  Reversed - <span></span>
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</body>
</html>


8. get( index )  Returns: Element
get( 인덱스 ), 실행후 매치 되는 원소를 반환

Access a single matched DOM element at a specified index in the matched set.
매치되는 원소들 중 주어진 인덱스에 해당하는 하나의 원소만 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("*", document.body).click(function (e) {
     e.stopPropagation();
     var domEl = $(this).get(0);
     $("span:first").text("Clicked on - " + domEl.tagName);
   });

  });
  </script>
  <style>
  span { color:red; }
  div { background:yellow; }
  </style>
</head>
<body>
  <span> </span>
  <p>In this paragraph is an <span>important</span> section</p>
  <div><input type="text" /></div>
</body>
</html>


9. index( subject )  Returns: Number
index( 객체 ), 실행후 숫자를 반환

Searches every matched element for the object and returns the index of the element, if found, starting with zero.
매치되어진 원소들에 대해 주어진 객체와 동일한것을 검색하여,
존재하면 그 원소들중에 몇번째에 해당하는가 하는 인덱스 번호를 반환한다.
인덱스는 0부터 시작한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div").click(function () {
     // this is the dom element clicked
     var index = $("div").index(this);
     $("span").text("That was div index #" + index);
   });

  });
  </script>
  <style>
  div { background:yellow; margin:5px; }
  span { color:red; }
  </style>
</head>
<body>
  <span>Click a div!</span>
  <div>First div</div>
  <div>Second div</div>
  <div>Third div</div>
</body>
</html>


10. jQuery.fn.extend( object )  Returns: jQuery
jQuery.fn.extend( 객체), 실행후 jQuery객체를 반환

Extends the jQuery element set to provide new methods (used to make a typical jQuery plugin).
제이쿼리에 새로운 함수를 확장한다.(플러그인으로 만들어 사용한다.)


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  jQuery.fn.extend({
   check: function() {
     return this.each(function() { this.checked = true; });
   },
   uncheck: function() {
     return this.each(function() { this.checked = false; });
   }
  });

  $(function(){

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

     $('input').check();
   });

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

     $('input').uncheck();
   });
  });
  </script>
  <style>
  div { background:yellow; margin:5px; }
  span { color:red; }
  </style>
</head>
<body>
<form>
<input type="checkbox" name="">
<input type="checkbox" name="">
<input type="checkbox" name="">
<input type="checkbox" name="">
<input type="checkbox" name="">
<input type="checkbox" name="">
</form>
<input type='button' id='button1' value='전체선택'>
<input type='button' id='button2' value='전체해제'>
</body>
</html>


11. jQuery.extend( object )  Returns: jQuery
jQuery.fn.extend( 객체), 실행후 jQuery객체를 반환

Extends the jQuery object itself.
제이쿼리 자체를 확장
아직은 잘 모르겟음


14. jQuery.noConflict( )  Returns: jQuery
jQuery.noConflict( ),  실행후 jQuery객체를 반환

Run this function to give control of the $ variable back to whichever library first implemented it.
아직은 잘 모르겠음


15. jQuery.noConflict( extreme )  Returns: jQuery
jQuery.noConflict( extreme ), 실행후 jQuery객체를 반환

Revert control of both the $ and jQuery variables to their original owners. Use with discretion.
아직은 잘 모르겠음




<Selectors>=>객체 선책

1. #id  Returns: Element
#아이디, 실행후 원소 반환

Matches a single element with the given id attribute.
주어진 아이디에 매치되는 원소하나를 찾아 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("#myDiv").css("border","3px solid red");
  });
  </script>
  <style>
  div {
   width: 90px;
   height: 90px;
   float:left;
   padding: 5px;
   margin: 5px;
   background-color: #EEEEEE;
  }
  </style>
</head>
<body>
  <div id="notMe"><p>id="notMe"</p></div>
  <div id="myDiv">id="myDiv"</div>
</body>
</html>


2. element  Returns: Array<Element>
원소명, 실행후 원소 배열 반환

Matches all elements with the given name.
주어진 원소명에 매치되는 모든 원소를 배열로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div").css("border","3px solid red");
  });
  </script>
  <style>
  div,span {
   width: 60px;
   height: 60px;
   float:left;
   padding: 10px;
   margin: 10px;
   background-color: #EEEEEE;
  }
  </style>
</head>
<body>
  <div>DIV1</div>
  <div>DIV2</div>
  <span>SPAN</span>
</body>
</html>


3. .class  Returns: Array<Element>
클래스명, 실행후 원소배열로 반환

Matches all elements with the given class.
주어진 클래스명에 매치되는 모든 원소를 배열로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $(".myClass").css("border","3px solid red");
  });
  </script>
  <style>
  div,span {
   width: 150px;
   height: 60px;
   float:left;
   padding: 10px;
   margin: 10px;
   background-color: #EEEEEE;
  }
  </style>
</head>
<body>
  <div class="notMe">div class="notMe"</div>
  <div class="myClass">div class="myClass"</div>
  <span class="myClass">span class="myClass"</span>
</body>
</html>


4. *  Returns: Array<Element>
모든것, 실행후 원소 배열로 반환

Matches all elements.
매치되는 모든 원소를 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("*").css("border","3px solid red");
  });
  </script>
  <style>
  div,span,p {
   width: 150px;
   height: 60px;
   float:left;
   padding: 10px;
   margin: 10px;
   background-color: #EEEEEE;
  }
  </style>
</head>
<body>
  <div>DIV</div>
  <span>SPAN</span>
  <p>P <button>Button</button></p>
</body>
</html>


5. selector1, selector2, selectorN  Returns: Array<Element>
selector1, selector2, selectorN, 실행후 원소배열로 반환

Matches the combined results of all the specified selectors.
주어진 것들에 대해 매치되는 모든 원소를 배열로 반환
구분자는 ,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div,span,p.myClass").css("border","3px solid red");
  });
  </script>
  <style>
  div,span,p {
   width: 130px;
   height: 60px;
   float:left;
   padding: 3px;
   margin: 2px;
   background-color: #EEEEEE;
   font-size:14px;
  }
  </style>
</head>
<body>
  <div>div</div>
  <p class="myClass">p class="myClass"</p>
  <p class="notMyClass">p class="notMyClass"</p>
  <span>span</span>
</body>
</html>


6. ancestor descendant  Returns: Array<Element>
조상 자손, 실행후 원소 배열로 반환

Matches all descendant elements specified by "descendant" of elements specified by "ancestor".
주어진 조상에 주어진 자손을 가진 모든 자손을 배열로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("form input").css("border", "2px dotted blue");
  });
  </script>
  <style>
  body { font-size:14px; }
  form { border:2px green solid; padding:2px; margin:0;
        background:#efe; }
  div { color:red; }
  fieldset { margin:1px; padding:3px; }
  </style>
</head>
<body>
  <form>
   <div>Form is surrounded by the green outline</div>
   <label>Child:</label>
   <input name="name" />
   <fieldset>
     <label>Grandchild:</label>
     <input name="newsletter" />
   </fieldset>
  </form>
  Sibling to form: <input name="none" />
</body>
</html>


7. parent > child  Returns: Array<Element>
조상 > 자손, 실행후 원소 배열 반환

Matches all child elements specified by "child" of elements specified by "parent".
주어진 조상에 포함된 주어진 자손에 매치되는 일단계 자손들만 모두 배열로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("#main > *").css("border", "3px double red");
  });
  </script>
  <style>
  body { font-size:14px; }
  span#main { display:block; background:yellow; height:110px; }
  button { display:block; float:left; margin:2px;
          font-size:14px; }
  div { width:90px; height:90px; margin:5px; float:left;
       background:#bbf; font-weight:bold; }
  div.mini { width:30px; height:30px; background:green; }
  </style>
</head>
<body>
  <span id="main">
   <div></div>
   <button>Child</button>
   <div class="mini"></div>
   <div>
     <div class="mini"></div>
     <div class="mini"></div>
   </div>
   <div><button>Grand</button></div>
   <div><span>A Span <em>in</em> child</span></div>
   <span>A Span in main</span>
  </span>
</body>
</html>


8. prev + next  Returns: Array<Element>
앞 뒤, 실행후 원소배열 반환

Matches all next elements specified by "next" that are next to elements specified by "prev".
주어진 앞원소와 뒤원소에 순차적으로 매치 되는 뒤원소들을 모두 배열로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("label + input").css("color", "blue").val("Labeled!")
  });
  </script>

</head>
<body>
  <form>
   <label>Name:</label>
   <input name="name" />
   <fieldset>
     <label>Newsletter:</label>
     <input name="newsletter" />
   </fieldset>
  </form>
  <input name="none" />
</body>
</html>


9. prev ~ siblings  Returns: Array<Element>
앞원소~형제 원소, 실행후 원소배열 반환

Matches all sibling elements after the "prev" element that match the filtering "siblings" selector.
주어진 앞원소와 형제인 뒤원소를 찾아 모두 배열로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("#prev ~ div").css("border", "3px groove blue");
  });
  </script>
  <style>
  div,span {
   display:block;
   width:80px;
   height:80px;
   margin:5px;
   background:#bbffaa;
   float:left;
   font-size:14px;
  }
  div#small {
   width:60px;
   height:25px;
   font-size:12px;
   background:#fab;
  }
  </style>
</head>
<body>
  <div>div (doesn't match since before #prev)</div>
  <div id="prev">div#prev</div>
  <div>div sibling</div>
  <div>div sibling <div id="small">div neice</div></div>
  <span>span sibling (not div)</span>
  <div>div sibling</div>
</body>
</html>


10. :first  Returns: Element
첫번째, 실행후 원소 반환

Matches the first selected element.
매치되는 원소들중 첫번째 것만 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("tr:first").css("font-style", "italic");
  });
  </script>
  <style>
  td { color:blue; font-weight:bold; }
  </style>
</head>
<body>
  <table>
   <tr><td>Row 1</td></tr>
   <tr><td>Row 2</td></tr>
   <tr><td>Row 3</td></tr>
  </table>
</body>
</html>


11. :last  Returns: Element
마지막, 실행후 원소 반환

Matches the last selected element.
매치되는 원소들중 마지막 것만 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("tr:last").css({backgroundColor: 'yellow', fontWeight: 'bolder'});
  });
  </script>

</head>
<body>
  <table>
   <tr><td>First Row</td></tr>
   <tr><td>Middle Row</td></tr>
   <tr><td>Last Row</td></tr>
  </table>
</body>
</html>


12. :not(selector)  Returns: Array<Element>
아니다, 실행후 원소 배열 반환

Filters out all elements matching the given selector.
주어진 것에 해당하지 않는 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("input:not(:checked) + span").css("background-color", "yellow");
   $("input").attr("disabled", "disabled");

  });
  </script>

</head>
<body>
  <div>
   <input type="checkbox" name="a" />
   <span>Mary</span>
  </div>
  <div>
   <input type="checkbox" name="b" />
   <span>Paul</span>
  </div>
  <div>
   <input type="checkbox" name="c" checked="checked" />
   <span>Peter</span>
  </div>
</body>
</html>


13. :even  Returns: Array<Element>
짝수, 실행후 원소 배열 반환

Matches even elements, zero-indexed.
매치된 원소들 중에서 인덱스가 짝수인것 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("tr:even").css("background-color", "#bbbbff");
  });
  </script>
  <style>
  table {
   background:#eeeeee;
  }
  </style>
</head>
<body>
  <table border="1">
   <tr><td>Row with Index #0</td></tr>
   <tr><td>Row with Index #1</td></tr>
   <tr><td>Row with Index #2</td></tr>
   <tr><td>Row with Index #3</td></tr>
  </table>
</body>
</html>


14. :odd  Returns: Array<Element>
홀수, 실행후 원소 배열 반환

Matches odd elements, zero-indexed.
매치된 원소들 중에서 인덱스가 홀수인것 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("tr:odd").css("background-color", "#bbbbff");
  });
  </script>
  <style>
  table {
   background:#f3f7f5;
  }
  </style>
</head>
<body>
  <table border="1">
   <tr><td>Row with Index #0</td></tr>
   <tr><td>Row with Index #1</td></tr>
   <tr><td>Row with Index #2</td></tr>
   <tr><td>Row with Index #3</td></tr>
  </table>
</body>
</html>


15. :eq(index)  Returns: Element
eq(인덱스), 실행후 원소  반환

Matches a single element by its index.
매치된 원소들 중에서 주어진 인덱스에 매치되는 원소 한개를 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("td:eq(2)").css("text-decoration", "blink");
  });
  </script>

</head>
<body>
  <table border="1">
   <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
   <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
   <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
  </table>
</body>
</html>


16. :gt(index)  Returns: Array<Element>
초과, 실행후 원소 배열 반환

Matches all elements with an index above the given one.
매치된 원소들 중에서 인덱스로 주어진 것보다 큰 인덱스 들을 모두 배열로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("td:gt(4)").css("text-decoration", "line-through");
  });
  </script>

</head>
<body>
  <table border="1">
   <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
   <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
   <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
  </table>
</body>
</html>


17. :lt(index)  Returns: Array<Element>
미만, 실행후 원소 배열 반환

Matches all elements with an index below the given one.
매치된 원소들 중에서 인덱스로 주어진 것보다 작은 인덱스 들을 모두 배열로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("td:lt(4)").css("color", "red");
  });
  </script>

</head>
<body>
  <table border="1">
   <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
   <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
   <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
  </table>
</body>
</html>


18. :header  Returns: Array<Element>
헤더, 실행후 원소 배열 반환

Matches all elements that are headers, like h1, h2, h3 and so on.
매치되는 원소들 중에서 h1, h2 ... 와 같은 헤더 태그들을 모두 배열로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $(":header").css({ background:'#CCC', color:'blue' });
  });
  </script>
  <style>
  body { font-size: 10px; font-family: Arial; }
  h1, h2 { margin: 3px 0; }
  </style>
</head>
<body>
  <h1>Header 1</h1>
  <p>Contents 1</p>
  <h2>Header 2</h2>
  <p>Contents 2</p>
</body>
</html>


19. :animated  Returns: Array<Element>
움직인다, 실행후 원소 배열 반환

Matches all elements that are currently being animated.
매치된 원소들 중에서 애니메이션이 동작하고 있는 것들을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("#run").click(function(){
     $("div:animated").toggleClass("colored");
   });
   function animateIt() {
     $("#mover").slideToggle("slow", animateIt);
   }
   animateIt();

  });
  </script>
  <style>
  div { background:yellow; border:1px solid #AAA; width:80px; height:80px; margin:5px; float:left; }
  div.colored { background:green; }
  </style>
</head>
<body>
  <button id="run">Run</button>
  <div></div>
  <div id="mover"></div>
  <div></div>
</body>
</html>


20. :contains(text)  Returns: Array<Element>
포함, 실행후 원소 배열 반환

Matches elements which contain the given text.
매치된 원소들 중에서 주어진 텍스트를 포함하는 것들을 모두 배열로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div:contains('John')").css("text-decoration", "underline");
  });
  </script>

</head>
<body>
  <div>John Resig</div>
  <div>George Martin</div>
  <div>Malcom John Sinclair</div>
  <div>J. Ohn
</body>
</html>


21. :empty  Returns: Array<Element>
비엇다. 실행후 원소 배열 반환

Matches all elements that are empty, be it elements or text.
매치된 원소들 중에서 텍스트가 비어있는 것들을 모두 배열로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("td:empty").text("Was empty!").css('background', 'rgb(255,220,200)');
  });
  </script>
  <style>
  td { text-align:center; }
  </style>
</head>
<body>
  <table border="1">
   <tr><td>TD #0</td><td></td></tr>
   <tr><td>TD #2</td><td></td></tr>
   <tr><td></td><td>TD#5</td></tr>
  </table>
</body>
</html>


22. :has(selector)  Returns: Array<Element>
has(selector), 실행후 원소 배열 반환

Matches elements which contain at least one element that matches the specified selector.
매치된 원소들 중에서 주어진 것을 포함하는 것을 모두 배열로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div:has(p)").addClass("test");
  });
  </script>
  <style>
  .test{ border: 3px inset red; }
  </style>
</head>
<body>
  <div><p>Hello in a paragraph</p></div>
  <div>Hello again! (with no paragraph)</div>
</body>
</html>


23. :parent  Returns: Array<Element>
부모, 실행후 원소 배열 반환

Matches all elements that are parents - they have child elements, including text.
주어진 것이 부모인 것을 모두 받아온다, 비어있는 것은 포함 안함

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("td:parent").fadeTo(1500, 0.3);
  });
  </script>
  <style>
td { width:40px; background:green; }
  </style>
</head>
<body>
  <table border="1">
   <tr><td>Value 1</td><td></td></tr>
   <tr><td>Value 2</td><td></td></tr>
  </table>
</body>
</html>


24. :hidden  Returns: Array<Element>
안보임, 실행후 원소 배열 반환

Matches all elements that are hidden, or input elements of type "hidden".
보이지 않는 모든 것들을 반환한다. none hidden  등, 추가로 input을 지정하면 인풋타입이 히든인것만 받아온다

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   // in some browsers :hidden includes head, title, script, etc... so limit to body
   $("span:first").text("Found " + $(":hidden", document.body).length +
                        " hidden elements total.");
   $("div:hidden").show(3000);
   $("span:last").text("Found " + $("input:hidden").length + " hidden inputs.");

  });
  </script>
  <style>
  div { width:70px; height:40px; background:#ee77ff; margin:5px; float:left; }
  span { display:block; clear:left; color:red; }
  .starthidden { display:none; }
  </style>
</head>
<body>
  <span></span>
  <div></div>
  <div style="display:none;">Hider!</div>
  <div></div>
  <div class="starthidden">Hider!</div>
  <div></div>
  <form>
   <input type="hidden" />
   <input type="hidden" />
   <input type="hidden" />
  </form>
  <span>
  </span>
</body>
</html>


25. :visible  Returns: Array<Element>
보임, 실행후 원소 배열 반환

Matches all elements that are visible.
보이는 것들을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div:visible").click(function () {
     $(this).css("background", "yellow");
   });
   $("button").click(function () {
     $("div:hidden").show("fast");
   });

  });
  </script>
  <style>
  div { width:50px; height:40px; margin:5px; border:3px outset green; float:left; }
  .starthidden { display:none; }
  </style>
</head>
<body>
  <button>Show hidden to see they don't change</button>
  <div></div>
  <div class="starthidden"></div>
  <div></div>
  <div></div>
  <div style="display:none;"></div>
</body>
</html>


26. [attribute]  Returns: Array<Element>
속성, 실행후 원소 배열 반환

Matches elements that have the specified attribute.
주어진 속성을 가진 것들을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div[id]").one("click", function(){
     var idString = $(this).text() + " = " + $(this).attr("id");
     $(this).text(idString);
   });

  });
  </script>

</head>
<body>
  <div>no id</div>
  <div id="hey">with id</div>
  <div id="there">has an id</div>
  <div>nope</div>
</body>
</html>


27. [attribute=value]  Returns: Array<Element>
속성=값, 실행후 원소 배열 반환

Matches elements that have the specified attribute with a certain value.
주어진 속성과 주어진 값이 일치 하는 모든것들을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("input[name='newsletter']").next().text(" is newsletter");
  });
  </script>

</head>
<body>
  <div>
   <input type="radio" name="newsletter" value="Hot Fuzz" />
   <span>name?</span>
  </div>
  <div>
   <input type="radio" name="newsletter" value="Cold Fusion" />
   <span>name?</span>
  </div>
  <div>
   <input type="radio" name="accept" value="Evil Plans" />
   <span>name?</span>
  </div>
</body>
</html>


28. [attribute!=value]  Returns: Array<Element>
속성!=값, 실행후 원소 배열 반환

Matches elements that don't have the specified attribute with a certain value.
주어진 속성과 주어진 값이 일치 하지 않는 모든것들을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("input[name!='newsletter']").next().text(" is not newsletter");
  });
  </script>

</head>
<body>
  <div>
   <input type="radio" name="newsletter" value="Hot Fuzz" />
   <span>name?</span>
  </div>
  <div>
   <input type="radio" name="newsletter" value="Cold Fusion" />
   <span>name?</span>
  </div>
  <div>
   <input type="radio" name="accept" value="Evil Plans" />
   <span>name?</span>
  </div>
</body>
</html>


29. [attribute^=value]  Returns: Array<Element>
속성^=값, 실행후 원소 배열 반환

Matches elements that have the specified attribute and it starts with a certain value.
주어진 속성을 가지며 값이 주어진 값으로 시작되는 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("input[name^='news']").val("news here!");
  });
  </script>

</head>
<body>
  <input name="newsletter" />
  <input name="milkman" />
  <input name="newsboy" />
</body>
</html>


30. [attribute$=value]  Returns: Array<Element>
속성$=값, 실행후 원소 배열 반환

Matches elements that have the specified attribute and it ends with a certain value.
주어진 속성을 가지며 값이 주어진 값으로 끝나는 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("input[name$='letter']").val("a letter");
  });
  </script>

</head>
<body>
  <input name="newsletter" />
  <input name="milkman" />
  <input name="jobletter" />
</body>
</html>


31. [attribute*=value]  Returns: Array<Element>
속성*=값, 실행후 원소 배열 반환

Matches elements that have the specified attribute and it contains a certain value.
주어진 속성을 가지며 값이 주어진 값을 포함하는 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("input[name*='man']").val("has man in it!");
  });
  </script>

</head>
<body>
  <input name="man-news" />
  <input name="milkman" />
  <input name="letterman2" />
  <input name="newmilk" />
</body>
</html>


32. [selector1][selector2][selectorN]  Returns: Array<Element>
속성들, 실행후 원소 배열 반환

Matches elements that have the specified attribute and it contains a certain value.
속성을 여러개 지정할수도 있다. 매치되는 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("input[id][name$='man']").val("only this one");
  });
  </script>

</head>
<body>
  <input id="man-news" name="man-news" />
  <input name="milkman" />
  <input id="letterman" name="new-letterman" />
  <input name="newmilk" />
</body>
</html>


33. :nth-child(index/even/odd/equation)  Returns: Array<Element>
몇번째 자식, 실행후 원소 배열 반환

Matches the nth-child of its parent or all its even or odd children.
인덱스나 키워드로 자식을 지정하여 매치되는 것은 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("ul li:nth-child(2)").append("<span> - 2nd!</span>");
  });
  </script>
  <style>
  div { float:left; }
  span { color:blue; }
  </style>
</head>
<body>
  <div><ul>
   <li>John</li>
   <li>Karl</li>
   <li>Brandon</li>
  </ul></div>
  <div><ul>
   <li>Sam</li>
  </ul></div>
  <div><ul>
   <li>Glen</li>
   <li>Tane</li>
   <li>Ralph</li>
   <li>David</li>
  </ul></div>
</body>
</html>


34. :first-child  Returns: Array<Element>
첫번째 자식, 실행후 원소 배열 반환

Matches the first child of its parent.
첫번째 자식에 매치되는 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div span:first-child")
       .css("text-decoration", "underline")
       .hover(function () {
             $(this).addClass("sogreen");
           }, function () {
             $(this).removeClass("sogreen");
           });

  });
  </script>
  <style>
  span { color:#008; }
  span.sogreen { color:green; font-weight: bolder; }
  </style>
</head>
<body>
  <div>
   <span>John,</span>
   <span>Karl,</span>
   <span>Brandon</span>
  </div>
  <div>
   <span>Glen,</span>
   <span>Tane,</span>
   <span>Ralph</span>
  </div>
</body>
</html>


35. :last-child  Returns: Array<Element>
마지막 자식, 실행후 원소 배열 반환

Matches the last child of its parent.
마지막 자식에 매치되는 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div span:last-child")
       .css({color:"red", fontSize:"80%"})
       .hover(function () {
             $(this).addClass("solast");
           }, function () {
             $(this).removeClass("solast");
           });

  });
  </script>
  <style>
  span.solast { text-decoration:line-through; }
  </style>
</head>
<body>
  <div>
   <span>John,</span>
   <span>Karl,</span>
   <span>Brandon,</span>
   <span>Sam</span>
  </div>
  <div>
   <span>Glen,</span>
   <span>Tane,</span>
   <span>Ralph,</span>
   <span>David</span>
  </div>
</body>
</html>


36. :only-child  Returns: Array<Element>
하나의 자식, 실행후 원소 배열 반환

Matches the only child of its parent.
하나의 자식으로만 이루어진 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div button:only-child").text("Alone").css("border", "2px blue solid");
  });
  </script>
  <style>
  div { width:100px; height:80px; margin:5px; float:left; background:#b9e }
  </style>
</head>
<body>
  <div>
   <button>Sibling!</button>
   <button>Sibling!</button>
  </div>
  <div>
   <button>Sibling!</button>
  </div>
  <div>
   None
  </div>
  <div>
   <button>Sibling!</button>
   <button>Sibling!</button>
   <button>Sibling!</button>
  </div>
  <div>
   <button>Sibling!</button>
  </div>
</body>
</html>


37. :input  Returns: Array<Element>
인풋, 실행후 원소 배열 반환

Matches all input, textarea, select and button elements.
인풋, 텍스트에리어, 셀렉트박스, 버튼들을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var allInputs = $(":input");
   var formChildren = $("form > *");
   $("div").text("Found " + allInputs.length + " inputs and the form has " +
                            formChildren.length + " children.")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


38. :text  Returns: Array<Element>
텍스트, 실행후 원소 배열 반환

Matches all input elements of type text.
인풋타입이 텍스트인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":text").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


39. :password  Returns: Array<Element>
패스워드, 실행후 원소 배열 반환

Matches all input elements of type password.
인풋타입이 패스워드인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":password").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


40. :radio  Returns: Array<Element>
레디오, 실행후 원소 배열 반환

Matches all input elements of type radio.
인풋타입이 레디오인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":radio").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" name="asdf" />
   <input type="radio" name="asdf" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>


41. :checkbox  Returns: Array<Element>
체크박스, 실행후 원소 배열 반환

Matches all input elements of type checkbox.
인풋타입이 체크박스인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":checkbox").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


42. :submit  Returns: Array<Element>
서브밋, 실행후 원소 배열 반환

Matches all input elements of type submit.
인풋타입이 서브밋인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":submit").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


43. :image  Returns: Array<Element>
이미지, 실행후 원소 배열 반환

Matches all input elements of type image.
인풋타입이 이미지인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":image").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


44.  :reset  Returns: Array<Element>
리셋, 실행후 원소 배열 반환

Matches all input elements of type reset.
인풋타입이 리셋인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":reset").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


45. :button  Returns: Array<Element>
버튼, 실행후 원소 배열 반환

Matches all input elements of type button.
인풋타입이 버튼인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":button").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


46. :file  Returns: Array<Element>
파일, 실행후 원소 배열 반환

Matches all input elements of type file.
인풋타입이 파일인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var input = $(":file").css({background:"yellow", border:"3px red solid"});
   $("div").text("For this type jQuery found " + input.length + ".")
           .css("color", "red");
   $("form").submit(function () { return false; }); // so it won't submit

  });
  </script>
  <style>
  textarea { height:45px; }
  </style>
</head>
<body>
  <form>
   <input type="button" value="Input Button"/>
   <input type="checkbox" />
   <input type="file" />
   <input type="hidden" />
   <input type="image" />
   <input type="password" />
   <input type="radio" />
   <input type="reset" />
   <input type="submit" />
   <input type="text" />
   <select><option>Option<option/></select>
   <textarea></textarea>
   <button>Button</button>
  </form>
  <div>
  </div>
</body>
</html>


47. :hidden  Returns: Array<Element>
히든, 실행후 원소 배열 반환

Matches all elements that are hidden, or input elements of type "hidden".
인풋타입이 히든인 것을 모두 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   // in some browsers :hidden includes head, title, script, etc... so limit to body
   $("span:first").text("Found " + $(":hidden", document.body).length +
                        " hidden elements total.");
   $("div:hidden").show(3000);
   $("span:last").text("Found " + $("input:hidden").length + " hidden inputs.");

  });
  </script>
  <style>
  div { width:70px; height:40px; background:#ee77ff; margin:5px; float:left; }
  span { display:block; clear:left; color:red; }
  .starthidden { display:none; }
  </style>
</head>
<body>
  <span></span>
  <div></div>
  <div style="display:none;">Hider!</div>
  <div></div>
  <div class="starthidden">Hider!</div>
  <div></div>
  <form>
   <input type="hidden" />
   <input type="hidden" />
   <input type="hidden" />
  </form>
  <span>
  </span>
</body>
</html>


48. :enabled  Returns: Array<Element>
활성화? 사용가능?, 실행후 원소 배열 반환

Matches all elements that are enabled.
활성화된 모든 것들을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("input:enabled").val("this is it");
  });
  </script>

</head>
<body>
  <form>
   <input name="email" disabled="disabled" />
   <input name="id" />
  </form>
</body>
</html>


49. :disabled  Returns: Array<Element>
비활성화? 사용불가능?, 실행후 원소 배열 반환

Matches all elements that are disabled.
비활성화된 모든 것들을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("input:disabled").val("this is it");
  });
  </script>

</head>
<body>
  <form>
   <input name="email" disabled="disabled" />
   <input name="id" />
  </form>
</body>
</html>


50. :checked  Returns: Array<Element>
체크됏음, 실행후 원소 배열 반환

Matches all elements that are checked.
인풋이 체크된 모든 것들을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   function countChecked() {
     var n = $("input:checked").length;
     $("div").text(n + (n == 1 ? " is" : " are") + " checked!");
   }
   countChecked();
   $(":checkbox").click(countChecked);

  });
  </script>
  <style>
  div { color:red; }
  </style>
</head>
<body>
  <form>
   <input type="checkbox" name="newsletter" checked="checked" value="Hourly" />
   <input type="checkbox" name="newsletter" value="Daily" />
   <input type="checkbox" name="newsletter" value="Weekly" />
   <input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
   <input type="checkbox" name="newsletter" value="Yearly" />
  </form>
  <div></div>
</body>
</html>


51. :selected  Returns: Array<Element>
선택되어짐, 실행후 원소 배열 반환

Matches all elements that are selected.
선택된 모든 것을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("select").change(function () {
         var str = "";
         $("select option:selected").each(function () {
               str += $(this).text() + " ";
             });
         $("div").text(str);
       })
       .trigger('change');

  });
  </script>
  <style>
  div { color:red; }
  </style>
</head>
<body>
  <select name="garden" multiple="multiple">
   <option>Flowers</option>
   <option selected="selected">Shrubs</option>
   <option>Trees</option>
   <option selected="selected">Bushes</option>
   <option>Grass</option>
   <option>Dirt</option>
  </select>
  <div></div>
</body>
</html>




<Attributes>

1. attr( name )  Returns: Object
속성 실행후 객체 반환

Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element. If the element does not have an attribute with such a name, undefined is returned.
주어진 속성명의 값을 가져옴, 매치되는 첫번째 것만 가져옴

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var title = $("em").attr("title");
   $("div").text(title);

  });
  </script>
  <style>
  em { color:blue; font-weight;bold; }
  div { color:red; }
  </style>
</head>
<body>
  <p>
   Once there was a <em title="huge, gigantic">large</em> dinosaur...
  </p>
  The title of the emphasis is:<div></div>
</body>
</html>


2. attr( properties )  Returns: jQuery
attr(속성배열) 실행후 jQuery객체를 반환

Set a key/value object as properties to all matched elements.
속성과 값들의 배열을 지정하여 적용

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("img").attr({
         src: "/images/hat.gif",
         title: "jQuery",
         alt: "jQuery Logo"
       });
   $("div").text($("img").attr("alt"));

  });
  </script>
  <style>
  img { padding:10px; }
  div { color:red; font-size:24px; }
  </style>
</head>
<body>
  <img />
  <img />
  <img />
  <div></div>
</body>
</html>


3. attr( key, value )  Returns: jQuery
attr( 속성, 값 ) 실행후 jQuery객체를 반환

Set a single property to a value, on all matched elements.
하나의 속성과 하나의 값만 지정하여 적용

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("button:gt(0)").attr("disabled","disabled");
  });
  </script>
  <style>
  button { margin:10px; }
  </style>
</head>
<body>
  <button>0th Button</button>
  <button>1st Button</button>
  <button>2nd Button</button>
</body>
</html>


4. attr( key, fn )  Returns: jQuery
attr(속성, 콜백함수) 실행후 jQuery 객체를 반환

Set a single property to a computed value, on all matched elements.
하나의 속성과 콜백함수를 지정하여 적용

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("img").attr("src", function() {
         return "/images/" + this.title;
       });

  });
  </script>

</head>
<body>
  <img title="hat.gif"/>
  <img title="hat-old.gif"/>
  <img title="hat2-old.gif"/>
</body>
</html>


5. removeAttr( name )  Returns: jQuery
속성 제거 실행후 jQuery 객체를 반환

Remove an attribute from each of the matched elements.
주어진 이름과 매치되는 속성을 제거

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("button").click(function () {
     $(this).next().removeAttr("disabled")
            .focus()
            .val("editable now");
   });

  });
  </script>

</head>
<body>
  <button>Enable</button>
  <input type="text" disabled="disabled" value="can't edit this" />
</body>
</html>


6. addClass( class )  Returns: jQuery
클래스 추가 실행후 jQuery 객체 반환

Adds the specified class(es) to each of the set of matched elements.
주어진 클래스 적용

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p:last").addClass("selected");
  });
  </script>
  <style>
  p { margin: 8px; font-size:16px; }
  .selected { color:red; }
  .highlight { background:yellow; }
  </style>
</head>
<body>
  <p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>
</body>
</html>


7. removeClass( class )  Returns: jQuery
클래스 제거 실행후 JQuery 객체를 리턴

Removes all or the specified class(es) from the set of matched elements.
주어진 클래스 제거

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p:even").removeClass("blue");
  });
  </script>
  <style>
  p { margin: 4px; font-size:16px; font-weight:bolder; }
  .blue { color:blue; }
  .under { text-decoration:underline; }
  .highlight { background:yellow; }
  </style>
</head>
<body>
  <p class="blue under">Hello</p>
  <p class="blue under highlight">and</p>
  <p class="blue under">then</p>
  <p class="blue under">Goodbye</p>
</body>
</html>


8. toggleClass( class )  Returns: jQuery
클래스 추가 삭제 반복 실행후 jQuery 객체 리턴

Adds the specified class if it is not present, removes the specified class if it is present.
주어진 클래스를 추가 삭제를 반복한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("p").click(function () {
     $(this).toggleClass("highlight");
   });

  });
  </script>
  <style>
  p { margin: 4px; font-size:16px; font-weight:bolder;
     cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:yellow; }
  </style>
</head>
<body>
  <p class="blue">Click to toggle</p>
  <p class="blue highlight">highlight</p>
  <p class="blue">on these</p>
  <p class="blue">paragraphs</p>
</body>
</html>


9. html( )  Returns: String
실행후 문자열을 반환

Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).
선택되어진 객체의 html을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("p").click(function () {
     var htmlStr = $(this).html();
     $(this).text(htmlStr);
   });

  });
  </script>
  <style>
  p { margin:8px; font-size:20px; color:blue;
     cursor:pointer; }
  b { text-decoration:underline; }
  button { cursor:pointer; }
  </style>
</head>
<body>
  <p>
   <b>Click</b> to change the <span id="tag">html</span>
  </p>
  <p>
   to a <span id="text">text</span> node.
  </p>
  <p>
   This <button name="nada">button</button> does nothing.
  </p>
</body>
</html>


10. html( val )  Returns: jQuery
실행후 jQuery 객체를 반환

Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
매치되는 모든 원소에 주어진 html을 넣는다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div").html("<span class='red'>Hello <b>Again</b></span>");
  });
  </script>
  <style>
  .red { color:red; }
  </style>
</head>
<body>
  <span>Hello</span>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>


11. text( )  Returns: String
실행후 문자열 반환

Get the text contents of all matched elements.
선택되어진 객체의 문자열을 반환한다. 태그는 제외된다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   var str = $("p:first").text();
   $("p:last").html(str);

  });
  </script>
  <style>
  p { color:blue; margin:8px; }
  b { color:red; }
  </style>
</head>
<body>
  <p><b>Test</b> Paragraph.</p>
  <p></p>
</body>
</html>


12. text( val )  Returns: jQuery
실행후 jQuery 객체 반환

Set the text contents of all matched elements.
매치되는 모든 원소에 주어진 텍스트를 집어넣는다. html을 넣는다 해도 텍스트화 된다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").text("<b>Some</b> new text.");
  });
  </script>
  <style>
  p { color:blue; margin:8px; }
  </style>
</head>
<body>
  <p>Test Paragraph.</p>
</body>
</html>


13. val( )  Returns: String, Array
실행후 문자열이나 배열로 반환

Get the content of the value attribute of the first matched element.
첫번째 매치되는 원소의 값을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   function displayVals() {
     var singleValues = $("#single").val();
     var multipleValues = $("#multiple").val() || [];
     $("p").html("<b>Single:</b> " +
                 singleValues +
                 " <b>Multiple:</b> " +
                 multipleValues.join(", "));
   }

   $("select").change(displayVals);
   displayVals();

  });
  </script>
  <style>
  p { color:red; margin:4px; }
  b { color:blue; }
  </style>
</head>
<body>
  <p></p>
  <select id="single">
   <option>Single</option>
   <option>Single2</option>
  </select>
  <select id="multiple" multiple="multiple">
   <option selected="selected">Multiple</option>
   <option>Multiple2</option>
   <option selected="selected">Multiple3</option>
  </select>
</body>
</html>


14. val( val )  Returns: jQuery
jQuery 객체를 반환

Set the value attribute of every matched element.
매치되는 모든 원소에 주어진 값을 적용한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("button").click(function () {
     var text = $(this).text();
     $("input").val(text);
   });

  });
  </script>
  <style>
  button { margin:4px; cursor:pointer; }
  input { margin:4px; color:blue; }
  </style>
</head>
<body>
  <div>
   <button>Feed</button>
   <button>the</button>
   <button>Input</button>
  </div>
  <input type="text" value="click a button" />
</body>
</html>


15. val( val )
반환 없음

Checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
체크 박스, 셀렉트 박스 레디오 버튼 셀렉트 옵션 등에 값을 적용
레디오나 체크박스 같은 경우는 값을 여러개 지정하여 할수 있다.
멀티플 같은 경우 배열로서 값을 지정할수 있다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("#single").val("Single2");
   $("#multiple").val(["Multiple2", "Multiple3"]);
   $("input").val(["check2", "radio1"]);

  });
  </script>
  <style>
  body { color:blue; }
  </style>
</head>
<body>
  <select id="single">
   <option>Single</option>
   <option>Single2</option>
  </select>
  <select id="multiple" multiple="multiple">
   <option selected="selected">Multiple</option>
   <option>Multiple2</option>
   <option selected="selected">Multiple3</option>
  </select><br/>
  <input type="checkbox" value="check1"/> check1
  <input type="checkbox" value="check2"/> check2
  <input type="radio" name="r" value="radio1"/> radio1
  <input type="radio" name="r" value="radio2"/> radio2
</body>
</html>



<Traversing>

1. eq( index )  Returns: jQuery
eq(인덱스) 실행후 jQuery 객체 반환

Reduce the set of matched elements to a single element.
매치되는 원소중 인덱스와 일치하는 것 하나만 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div").eq(2).addClass("red");

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:10px; float:left;
       border:2px solid blue; }
  .red { background:red; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>


2. hasClass( class )  Returns: Boolean
클래스가 있나 없나 실행후 참거짓 리턴

Checks the current selection against a class and returns true, if at least one element of the selection has the given class.
매치되는 원소에 주어진 클래스가 존재하면 참, 아니면 거짓을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div").click(function(){
     if ( $(this).hasClass("protected") )
       $(this).animate({ left: -10 }, 75)
              .animate({ left: 10 }, 75)
              .animate({ left: -10 }, 75)
              .animate({ left: 10 }, 75)
              .animate({ left: 0 }, 75);
   });

  });
  </script>
  <style>
  div { width: 80px; height: 80px; background: #abc;
       position: relative; border: 2px solid black;
       margin: 20px 0px; float: left; left:0 }
  div.protected { border-color: red; }
  span { display:block; float:left; width:20px;
        height:20px; }
  </style>
</head>
<body>
  <span></span><div class="protected"></div>
  <span></span><div></div>
  <span></span><div></div>
  <span></span><div class="protected"></div>
</body>
</html>


3. filter( expr )  Returns: jQuery
실행후 jQuery 객체를 반환

Removes all elements from the set of matched elements that do not match the specified expression(s).
매치되는 원소들중 해당 필터 표현에 맞지 않는 것들은 제거하고 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div").css("background", "#c8ebcc")
           .filter(".middle")
           .css("border-color", "red");

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:5px; float:left;
       border:2px white solid;}
  </style>
</head>
<body>
  <div></div>
  <div class="middle"></div>
  <div class="middle"></div>
  <div class="middle"></div>
  <div class="middle"></div>
  <div></div>
</body>
</html>


4. filter( fn )  Returns: jQuery
filter(함수) 실행후 jQuery 객체를 반환

Removes all elements from the set of matched elements that does not match the specified function.
매치되는 원소들중 해당 필터 함수에 맞지 않는 것들은 제거하고 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div").css("background", "#b4b0da")
           .filter(function (index) {
                 return index == 1 || $(this).attr("id") == "fourth";
               })
           .css("border", "3px double red");

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:5px; float:left;
       border:3px white solid; }
  </style>
</head>
<body>
  <div id="first"></div>
  <div id="second"></div>
  <div id="third"></div>
  <div id="fourth"></div>
  <div id="fifth"></div>
  <div id="sixth"></div>
</body>
</html>


5. is( expr )  Returns: Boolean
존재 여부 실행후 참거짓 반환

Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.
매치되는 원소들중 주어진 표현식과 비교하여 일치 하면 참, 그렇지 않으면 거짓을 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div").one('click', function () {
     if ($(this).is(":first-child")) {
       $("p").text("It's the first div.");
     } else if ($(this).is(".blue,.red")) {
       $("p").text("It's a blue or red div.");
     } else if ($(this).is(":contains('Peter')")) {
       $("p").text("It's Peter!");
     } else {
       $("p").html("It's nothing <em>special</em>.");
     }
     $("p").hide().slideDown("slow");
     $(this).css({"border-style": "inset", cursor:"default"});
   });

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:5px; float:left;
       border:4px outset; background:green; text-align:center;
       font-weight:bolder; cursor:pointer; }
  .blue { background:blue; }
  .red { background:red; }
  span { color:white; font-size:16px; }
  p { color:red; font-weight:bolder; background:yellow;
     margin:3px; clear:left; display:none; }
  </style>
</head>
<body>
  <div></div>
  <div class="blue"></div>
  <div></div>
  <div class="red"></div>
  <div><br/><span>Peter</span></div>
  <div class="blue"></div>
  <p> </p>
</body>
</html>


16. map( callback )  Returns: jQuery
map(콜백함수) 실행후 jQuery  객체 반환

Translate a set of elements in the jQuery object into another set of values in an array (which may, or may not, be elements).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("p").append( $("input").map(function(){
     return $(this).val();
   }).get().join(", ") );

  });
  </script>
  <style>
  p { color:red; }
  </style>
</head>
<body>
  <p><b>Values: </b></p>
  <form>
   <input type="text" name="name" value="John"/>
   <input type="text" name="password" value="password"/>
   <input type="text" name="url" value="http://ejohn.org/"/>
  </form>
</body>
</html>


17. not( expr )  Returns: jQuery
실행후 jQuery 객체 반환

Removes elements matching the specified expression from the set of matched elements.
매치되는 원소들중 표현식과 일치 하는 원소는 제거 하고 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("div").not(".green, #blueone")
           .css("border-color", "red");

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:10px; float:left;
       background:yellow; border:2px solid white; }
  .green { background:#8f8; }
  .gray { background:#ccc; }
  #blueone { background:#99f; }
  </style>
</head>
<body>
  <div></div>
  <div id="blueone"></div>
  <div></div>
  <div class="green"></div>
  <div class="green"></div>
  <div class="gray"></div>
  <div></div>
</body>
</html>


18. slice( start, end )  Returns: jQuery
Selects a subset of the matched elements.
매치되어진 원소들 중에서 해당 시작인덱스와 끝 인덱스의 범위에 있는 인덱스의 원소들을 모두 배열로 반환한다.
끝 인덱스를 지정하지 않으면 시작인덱스 부터 끝까지 배열로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   function colorEm() {
     var $div = $("div");
     var start = Math.floor(Math.random() *
                            $div.length);
     var end = Math.floor(Math.random() *
                          ($div.length - start)) +
                          start + 1;
     if (end == $div.length) end = undefined;
     $div.css("background", "");
     if (end)
       $div.slice(start, end).css("background", "yellow");  
      else
       $div.slice(start).css("background", "yellow");
    
     $("span").text('$("div").slice(' + start +
                    (end ? ', ' + end : '') +
                    ').css("background", "yellow");');
   }

   $("button").click(colorEm);

  });
  </script>
  <style>
  div { width:40px; height:40px; margin:10px; float:left;
       border:2px solid blue; }
  span { color:red; font-weight:bold; }
  button { margin:5px; }
  </style>
</head>
<body>
  <button>Turn slice yellow</button>
  <span>Click the button!</span>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>


19. add( expr )  Returns: jQuery
add( expr ), 실행후 jQuery 객체 반환

Adds more elements, matched by the given expression, to the set of matched elements.
매치된 원소에 새로운 원소나 원소들을 추가한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("div").css("border", "2px solid red")
           .add("p")
           .css("background", "yellow");

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:10px; float:left; }
  p { clear:left; font-weight:bold; font-size:16px;
     color:blue; margin:0 10px; padding:2px; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <p>Added this... (notice no border)</p>
</body>
</html>


20. children( expr )  Returns: jQuery
children( expr ), 실행후 jQuery 객체 반환

Get a set of elements containing all of the unique children of each of the matched set of elements.
선택되어진 원소의 자식들을 반환
이해가 잘 안됨

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("#container").click(function (e) {
     $("*").removeClass("hilite");
     var $kids = $(e.target).children();
     var len = $kids.addClass("hilite").length;

     $("#results span:first").text(len);
     $("#results span:last").text(e.target.tagName);

     e.preventDefault();
     return false;
   });

  });
  </script>
  <style>
  body { font-size:16px; font-weight:bolder; }
  div { width:130px; height:82px; margin:10px; float:left;
       border:1px solid blue; padding:4px; }
  #container { width:auto; height:105px; margin:0; float:none;
       border:none; }
  .hilite { border-color:red; }
  #results { display:block; color:red; }
  p { margin:10px; border:1px solid transparent; }
  span { color:blue; border:1px solid transparent; }
  input { width:100px; }
  em { border:1px solid transparent; }
  a { border:1px solid transparent; }
  b { border:1px solid transparent; }
  button { border:1px solid transparent; }
  </style>
</head>
<body>
  <div id="container">
   <div>
     <p>This <span>is the <em>way</em> we</span>
     write <em>the</em> demo,</p>
   </div>
   <div>
     <a href="#"><b>w</b>rit<b>e</b></a> the <span>demo,</span> <button>write
     the</button> demo,
   </div>
   <div>
     This <span>the way we <em>write</em> the <em>demo</em> so</span>
     <input type="text" value="early" /> in
   </div>
   <p>
     <span>t</span>he <span>m</span>orning.
     <span id="results">Found <span>0</span> children in <span>TAG</span>.</span>
   </p>
  </div>
</body>
</html>


21. contents( )  Returns: jQuery
contents( ), 실행후 jQuery 객체 반환

Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
매치된 원소들중에서 비어있지 않는 자식들을 모두 가져옴
이해가 잘 안됨

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").contents().not("[@nodeType=1]").wrap("<b/>");
  });
  </script>
 
</head>
<body>
  <p>Hello <a href="Johnhttp://ejohn.org/">John</a>, how are you doing?</p>
</body>
</html>


22. find( expr )  Returns: jQuery
find( expr ), 실행후 jQuery 객체 반환

Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.
매치되어진 원소들 중에서 주어진 것에 매치되는 것을 찾아 그것들을 모두 배열로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").find("span").css('color','red');
  });
  </script>
 
</head>
<body>
  <p><span>Hello</span>, how are you?</p>
  <p>Me? I'm <span>good</span>.</p>
</body>
</html>


23. next( expr )  Returns: jQuery
next( expr ), 실행후 jQuery 객체 반환

Get a set of elements containing the unique next siblings of each of the matched set of elements.
매치되어진 원소와 형제 관계인 바로 다음 원소를 찾아 객체로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("button").click(function () {
     var txt = $(this).text();
     $(this).next().text(txt);
   });

  });
  </script>
  <style>
  span { color:blue; font-weight:bold; }
  button { width:100px; }
  </style>
</head>
<body>
  <div><button>First</button> - <span></span></div>
  <div><button>Second</button> - <span></span></div>
  <div><button>Third</button> - <span></span></div>
</body>
</html>


24. nextAll( expr )  Returns: jQuery
nextAll( expr ), 실행후 jQuery 객체 반환

Find all sibling elements after the current element.
현재 매치되어진 원소와 형제 관계에 있는 모든 원소를 찾아 객체로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div:first").nextAll().addClass("after");
  });
  </script>
  <style>
  div { width: 80px; height: 80px; background: #abc;
       border: 2px solid black; margin: 10px; float: left; }
  div.after { border-color: red; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>


25. parent( expr )  Returns: jQuery
parent( expr ), 실행후 jQuery 객체 반환

Get a set of elements containing the unique parents of the matched set of elements.
매치되어진 원소의 유일한 부모를 찾아 객체로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("*", document.body).each(function () {
     var parentTag = $(this).parent().get(0).tagName;
     $(this).prepend(document.createTextNode(parentTag + " > "));
   });

  });
  </script>
  <style>
  div,p { margin:10px; }
  </style>
</head>
<body>
  <div>div,
   <span>span, </span>
   <b>b </b>
  </div>
  <p>p,
   <span>span,
     <em>em </em>
   </span>
  </p>
  <div>div,
   <strong>strong,
     <span>span, </span>
     <em>em,
       <b>b, </b>
     </em>
   </strong>
   <b>b </b>
  </div>
</body>
</html>


26. parents( expr )  Returns: jQuery
parents( expr ), 실행후 jQuery 객체 반환

Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
매치되어진 원소의 유일한 조상들을 찾아 객체로 반환한다.

The matched elements can be filtered with an optional expression.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   var parentEls = $("b").parents()
                         .map(function () {
                               return this.tagName;
                             })
                         .get().join(", ");
   $("b").append("<strong>" + parentEls + "</strong>");

  });
  </script>
  <style>
  b { color:blue; }
  strong { color:red; }
  </style>
</head>
<body>
  <div>
   <p>
     <span>
       <b>My parents are: </b>
     </span>
   </p>
  </div>
</body>
</html>



27. prev( expr )  Returns: jQuery
prev( expr ), 실행후 jQuery 객체 반환

Get a set of elements containing the unique previous siblings of each of the matched set of elements.
매치되어진 원소 보다 앞에 있는 유니크한 형제 원소를 찾아 객체로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   var $curr = $("#start");
   $curr.css("background", "#f99");
   $("button").click(function () {
     $curr = $curr.prev();
     $("div").css("background", "");
     $curr.css("background", "#f99");
   });

  });
  </script>
  <style>
  div { width:40px; height:40px; margin:10px;
       float:left; border:2px blue solid;
       padding:2px; }
  span { font-size:14px; }
  p { clear:left; margin:10px; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div><span>has child</span></div>
  <div></div>
  <div></div>
  <div></div>
  <div id="start"></div>
  <div></div>
  <p><button>Go to Prev</button></p>
</body>
</html>


28. prevAll( expr )  Returns: jQuery
prevAll( expr ), 실행후 jQuery 객체 반환

Find all sibling elements before the current element.
매치되어진 원소보다 이전에 있는 모든 형제 원소를 찾아 객체로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div:last").prevAll().addClass("before");
  });
  </script>
  <style>
  div { width:70px; height:70px; background:#abc;
       border:2px solid black; margin:10px; float:left; }
  div.before { border-color: red; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>


29. siblings( expr )  Returns: jQuery
siblings( expr ), 실행후 jQuery 객체 반환

Get a set of elements containing all of the unique siblings of each of the matched set of elements.
매치되어진 원소들의 모든 형제 원소들을 찾아 반환한다.

Can be filtered with an optional expressions.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   var len = $(".hilite").siblings()
                         .css("color", "red")
                         .length;
   $("b").text(len);

  });
  </script>
  <style>
  ul { float:left; margin:5px; font-size:16px; font-weight:bold; }
  p { color:blue; margin:10px 20px; font-size:16px; padding:5px;
     font-weight:bolder; }
  .hilite { background:yellow; }
</style>
</head>
<body>
  <ul>
   <li>One</li>
   <li>Two</li>
   <li class="hilite">Three</li>
   <li>Four</li>
  </ul>
  <ul>
   <li>Five</li>
   <li>Six</li>
   <li>Seven</li>
  </ul>
  <ul>
   <li>Eight</li>
   <li class="hilite">Nine</li>
   <li>Ten</li>
   <li class="hilite">Eleven</li>
  </ul>
  <p>Unique siblings: <b></b></p>
</body>
</html>


30. andSelf( )  Returns: jQuery
andSelf( ), 실행후 jQuery 객체 반환

Add the previous selection to the current selection.
매치되어진 원소들의 상위의 형제 원소들과 조상 원소 모두를 찾아 추가하여 객체로 반환한다.
이해가 잘 안됨

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("div").find("p").andSelf().addClass("border");
   $("div").find("p").addClass("background");

  });
  </script>
  <style>
  p, div { margin:5px; padding:5px; }
  .border { border: 2px solid red; }
  .background { background:yellow; }
  </style>
</head>
<body>
  <div>
   <p>First Paragraph</p>
   <p>Second Paragraph</p>
  </div>
</body>
</html>


31. end( )  Returns: jQuery
end( ), 실행후 jQuery 객체 반환

Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state (right before the destructive operation).
현재 보다 이전의 매치상태로 돌아가서 객체를 반환
잘 이해가 안됨

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   jQuery.fn.showTags = function (n) {
     var tags = this.map(function () {
                             return this.tagName;
                           })
                       .get().join(", ");
     $("b:eq(" + n + ")").text(tags);
     return this;
   };

   $("p").showTags(0)
         .find("span")
         .showTags(1)
         .css("background", "yellow")
         .end()
         .showTags(2)
         .css("font-style", "italic");

  });
  </script>
  <style>
  p, div { margin:1px; padding:1px; font-weight:bold;
          font-size:16px; }
  div { color:blue; }
  b { color:red; }
  </style>
</head>
<body>
  <p>
   Hi there <span>how</span> are you <span>doing</span>?
  </p>
  <p>
   This <span>span</span> is one of
   several <span>spans</span> in this
   <span>sentence</span>.
  </p>
  <div>
   Tags in jQuery object initially: <b></b>
  </div>
  <div>
   Tags in jQuery object after find: <b></b>
  </div>
  <div>
   Tags in jQuery object after end: <b></b>
  </div>
</body>
</html>



<Manipulation>

1. html( )  Returns: String
html( ), 실행후 문자열 반환

Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).
매치되어진 첫번째 원소의 html을 가져와서 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("p").click(function () {
     var htmlStr = $(this).html();
     $(this).text(htmlStr);
   });

  });
  </script>
  <style>
  p { margin:8px; font-size:20px; color:blue;
     cursor:pointer; }
  b { text-decoration:underline; }
  button { cursor:pointer; }
  </style>
</head>
<body>
  <p>
   <b>Click</b> to change the <span id="tag">html</span>
  </p>
  <p>
   to a <span id="text">text</span> node.
  </p>
  <p>
   This <button name="nada">button</button> does nothing.
  </p>
</body>
</html>



2. html( val )  Returns: jQuery
html( val ), 실행후 jQuery 객체 반환

Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).

매치되는 모든 원소들에게 주어진 html을 삽입하고 객체를 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("div").html("<span class='red'>Hello <b>Again</b></span>");
  });
  </script>
  <style>
  .red { color:red; }
  </style>
</head>
<body>
  <span>Hello</span>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>


3. text( )  Returns: String
text( ), 실행후 문자열 반환

Get the text contents of all matched elements.
매치되어진 원소의 태그를 제외한 문자열만 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   var str = $("p:first").text();
   $("p:last").html(str);

  });
  </script>
  <style>
  p { color:blue; margin:8px; }
  b { color:red; }
  </style>
</head>
<body>
  <p><b>Test</b> Paragraph.</p>
  <p></p>
</body>
</html>


4. text( val )  Returns: jQuery
text( val ), 실행후 jQuery 객체 반환

Set the text contents of all matched elements.
매치된 원소들에 주어진 문자열을 삽입하고 객체를 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").text("<b>Some</b> new text.");
  });
  </script>
  <style>
  p { color:blue; margin:8px; }
  </style>
</head>
<body>
  <p>Test Paragraph.</p>
</body>
</html>


5. append( content )  Returns: jQuery
append( content ) , 실행후 jQuery 객체 반환

Append content to the inside of every matched element.
매치되어진 원소에 주어진 내용을 추가로 삽입한 후 객체 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").append("<b>Hello</b>");
  });
  </script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>I would like to say: </p>
</body>
</html>


6. appendTo( content )  Returns: jQuery
appendTo( content ), 실행후 jQuery 객체 반환

Append all of the matched elements to another, specified, set of elements.
매치되어진 원소들의 내용들을 주어진 조건에 맞는 원소에 추가로 삽입한후  객체 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("span").appendTo("#foo"); // check append() examples
  });
  </script>
  <style>#foo { background:yellow; }</style>
</head>
<body>
  <span>I have nothing more to say... </span>
  <div id="foo">FOO! </div>
</body>
</html>


7. prepend( content )  Returns: jQuery
prepend( content ), 실행후 jQuery 객체 반환

Prepend content to the inside of every matched element.
매치되어진 원소들에 맨앞에 주어진 내용을 삽입한후 객체를 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").prepend("<b>Hello </b>");
  });
  </script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>there friend!</p>
  <p>amigo!</p>
</body>
</html>


8. prependTo( content )  Returns: jQuery
prependTo( content )  실행후 jQuery 객체 반환

Prepend all of the matched elements to another, specified, set of elements.
매칮되어진 원소의 내용을 주어진 것에 매치되는 원소의 맨앞에 추가 삽입한후 객체를 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("span").prependTo("#foo"); // check prepend() examples
  });
  </script>
  <style>div { background:yellow; }</style>
</head>
<body>
  <div id="foo">FOO!</div>
  <span>I have something to say... </span>
</body>
</html>


9. after( content )  Returns: jQuery
after( content ), 실행후 jQuery 객체를 반환

Insert content after each of the matched elements.
매치되는 모든 원소의 뒤에 주어진 내용을 삽입

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").after("<b>Hello</b>");
  });
  </script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>I would like to say: </p>
</body>
</html>


10. before( content )  Returns: jQuery
before( content )  실행후 jQuery 객체를 반환

Insert content before each of the matched elements.

매치되는 모는 원소의 앞에 주어진 내용 삽입
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").before("<b>Hello</b>");
  });
  </script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p> is what I said...</p>
</body>
</html>


11. insertAfter( content )  Returns: jQuery
insertAfter( content ), 실행후 jQuery 객체 반환

Insert all of the matched elements after another, specified, set of elements.
매치되어진 원소들을 주어진 것에 매치되는 원소의 뒤에 삽입한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").insertAfter("#foo"); // check after() examples
  });
  </script>
  <style>#foo { background:yellow; }</style>
</head>
<body>
  <p> is what I said... </p><div id="foo">FOO!</div>
</body>
</html>


12. insertBefore( content )  Returns: jQuery
insertBefore( content ), 실행후 jQuery 객체 반환

Insert all of the matched elements before another, specified, set of elements.
매치되어진 원소앞에 주어진 것에 매치된 원소를 삽입한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").insertBefore("#foo"); // check before() examples
  });
  </script>
  <style>#foo { background:yellow; }</style>
</head>
<body>
  <div id="foo">FOO!</div><p>I would like to say: </p>
</body>
</html>


13. wrap( html )  Returns: jQuery
wrap( html ), 실행후 jQuery 객체를 반환

Wrap all matched elements with a structure of other elements.
매치되어진 원소를 주어진 html로서 감싼후 객체를 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("span").wrap("<div><div><p><em><b></b></em></p></div></div>");
  });
  </script>
  <style>
  div { border:2px blue solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }
  </style>
</head>
<body>
  <span>Span Text</span>
  <span>Another One</span>
</body>
</html>


14. wrap( elem )  Returns: jQuery
wrap( elem ), 실행후 jQuery 객체 반환

Wrap all matched elements with a structure of other elements.
매치된 모든 원소를 주어진것에 매치되는 원소로 감싼다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").wrap(document.getElementById('content'));
  });
  </script>
  <style>#content { background:#9f9; }</style>
</head>
<body>
  <p>Test Paragraph.</p><div id="content"></div>
</body>
</html>


15. wrapAll( html )  Returns: jQuery
wrapAll( html )  실행후 jQuery 객체 반환

Wrap all the elements in the matched set into a single wrapper element.
매치되는 원소들을 주어진 html로 모두 하나로 감싼다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("span").wrapAll("<div><div><p><em><b></b></em></p></div></div>");
  });
  </script>
  <style>
  div { border:2px blue solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }
  strong { color:red; }
  </style>
</head>
<body>
  <span>Span Text</span>
  <strong>What about me?</strong>
  <span>Another One</span>
</body>
</html>


16. wrapAll( elem )  Returns: jQuery
wrapAll( elem ), 실행후 jQuery 객체 반환

Wrap all the elements in the matched set into a single wrapper element.
매치되어진 원소들을 주어진 것에 매치되는 것으로 하나로 감싼다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").wrapAll(document.createElement("div"));
  });
  </script>
  <style>
  div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }
  </style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
</body>
</html>



17. wrapInner( html )  Returns: jQuery
wrapInner( html ), 실행후 jQuery 객체 반환

Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.
매치되어진 원소 속의 내용을 주어진 것으로 감싼다

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("body").wrapInner("<div><div><p><em><b></b></em></p></div></div>");
  });
  </script>
  <style>
  div { border:2px green solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }
  </style>
</head>
<body>
  Plain old text, or is it?
</body>
</html>


18. wrapInner( elem )  Returns: jQuery
wrapInner( elem ), 실행후 jQuery 객체를 반환

Wrap the inner child contents of each matched element (including text nodes) with a DOM element.
매치되어진 원소 속의 내용을 주어진 것에 매치된것으로 감싼다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").wrapInner(document.createElement("b"));
  });
  </script>
  <style>p { background:#9f9; }</style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
</body>
</html>


19. replaceWith( content )  Returns: jQuery
replaceWith( content ), 실행후 jQuery 객체 반환

Replaces all matched elements with the specified HTML or DOM elements.
매치되어진 원소를 주어진 내용과 치환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("button").click(function () {
     $(this).replaceWith("<div>" + $(this).text() + "</div>");
   });

  });
  </script>
  <style>
  button { display:block; margin:3px; color:red; width:200px; }
  div { color:red; border:2px solid blue; width:200px;
       margin:3px; text-align:center; }
  </style>
</head>
<body>
  <button>First</button>
  <button>Second</button>
  <button>Third</button>
</body>
</html>


20. replaceAll( selector )  Returns: jQuery
replaceAll( selector ), 실행후 jQuery 객체 반환

Replaces the elements matched by the specified selector with the matched elements.
매치되어진 것들을 주어진 것에 매치되는 것에 모두 바꿈

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("<b>Paragraph. </b>").replaceAll("p"); // check replaceWith() examples
  });
  </script>
 
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
</body>
</html>


21. empty( )  Returns: jQuery
empty( )  실행후 jQuery 객체 반환

Remove all child nodes from the set of matched elements.
매치되어진 모든 것들을 없앤다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("button").click(function () {
     $("p").empty();
   });

  });
  </script>
  <style>
  p { background:yellow; }
  </style>
</head>
<body>
  <p>
   Hello, <span>Person</span> <a href=";">and person</a>
  </p>
  <button>Call empty() on above paragraph</button>
</body>
</html>


22. remove( expr )  Returns: jQuery
remove( expr ), 실행후 jQuery 객체를 반환

Removes all matched elements from the DOM.
매치되는 모든 원소를 옮기다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("button").click(function () {
     $("p").remove();
   });

  });
  </script>
  <style>p { background:yellow; margin:6px 0; }</style>
</head>
<body>
  <p>Hello</p>
  how are
  <p>you?</p>
  <button>Call remove() on paragraphs
</body>
</html>


23. clone( )  Returns: jQuery
clone( )  실행후 jQuery 객체 반환

Clone matched DOM Elements and select the clones.
선택되어진 원소를 복사

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("b").clone().prependTo("p");
  });
  </script>
 
</head>
<body>
  <b>Hello</b><p>, how are you?</p>
</body>
</html>


24. clone( true )  Returns: jQuery
clone( true )  실행후 jQuery 객체 반환

Clone matched DOM Elements, and all their event handlers, and select the clones.
완벽한 복사

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("button").click(function(){
     $(this).clone(true).insertAfter(this);
   });

  });
  </script>
 
</head>
<body>
  <button>Clone Me!</button>
</body>
</html>



<CSS>

1. css( name )  Returns: String
css( name )  실행후 문자열 반환

Return a style property on the first matched element.
매치된 원소에서 주어진 스타일 속성이 발견되면 그 값을 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("div").click(function () {
     var color = $(this).css("background-color");
     $("#result").html("That div is <span style='color:" +
                        color + ";'>" + color + "</span>.");
   });

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:5px; float:left; }
  </style>
</head>
<body>
  <span id="result"> </span>
  <div style="background-color:blue;"></div>
  <div style="background-color:rgb(15,99,30);"></div>
  <div style="background-color:#123456;"></div>
  <div style="background-color:#f11;"></div>
</body>
</html>


2. css( properties )  Returns: jQuery
css( properties )  실행후 jQuery 객체 반환

Set a key/value object as style properties to all matched elements.
매치되어진 모든 원소에 주어진 키와 값으로 이루어진 속성들의 배열의 스타일을 적용하고 객체를 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("p").hover(function () {
     $(this).css({ "background-color":"yellow", "font-weight":"bolder" });
   }, function () {
     var cssObj = {
       "background-color": "#ddd",
       "font-weight": "",
       color: "rgb(0,40,244)"
     }
     $(this).css(cssObj);
   });

  });
  </script>
  <style>
  p { color:green; }
  </style>
</head>
<body>
  <p>
   Move the mouse over a paragraph.
  </p>
  <p>
   Like this one or the one above.
  </p>
</body>
</html>


3. css( name, value )  Returns: jQuery
css( name, value )  실행후 jQuery 객체 반환

Set a single style property to a value on all matched elements.
하나의 속성과 값을 받아 매치되어진 모든 원소에 적용

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("p").mouseover(function () {
     $(this).css("color","red");
   });

  });
  </script>
  <style>
  p { color:blue; width:200px; font-size:14px; }
  </style>
</head>
<body>
  <p>
   Just roll the mouse over me.
  </p>
  <p>
   Or me to see a color change.
  </p>
</body>
</html>


4. offset( )  Returns: Object{top,left}
offset( )  실행후 탑과 레프트에 해당하는 위치 정보를 반환

Get the current offset of the first matched element relative to the viewport.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
  });
  </script>
  <style>
  p { margin-left:10px; }
  </style>
</head>
<body>
  <p>Hello</p><p>2nd Paragraph</p>
</body>
</html>


5. height( )  Returns: Integer
height( )  실행후 정수형을 반환한다.

Get the current computed, pixel, height of the first matched element.
매치된 첫번째 원소의 높이를 픽셀로 반환한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   function showHeight(ele, h) {
     $("div").text("The height for the " + ele +
                   " is " + h + "px.");
   }
   $("#getp").click(function () {
     showHeight("paragraph", $("p").height());
   });
   $("#getd").click(function () {
     showHeight("document", $(document).height());
   });
   $("#getw").click(function () {
     showHeight("window", $(window).height());
   });

  });
  </script>
  <style>
  body { background:yellow; }
  button { font-size:12px; margin:2px; }
  p { width:150px; border:1px red solid; }
  div { color:red; font-weight:bold; }
  </style>
</head>
<body>
  <button id="getp">Get Paragraph Height</button>
  <button id="getd">Get Document Height</button>
  <button id="getw">Get Window Height</button>
  <div> </div>
  <p>
   Sample paragraph to test height
  </p>
</body>
</html>


6. height( val )  Returns: jQuery
height( val )  실행후 jQuery 객체 반환

Set the CSS height of every matched element.
매치되는 모든 원소에 주어진 높이를 적용한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("div").one('click', function () {
     $(this).height(30)
            .css({cursor:"auto", backgroundColor:"green"});
   });

  });
  </script>
  <style>
  div { width:50px; height:70px; float:left; margin:5px;
       background:rgb(255,140,0); cursor:pointer; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>


7. width( )  Returns: Integer
width( )  실행후 정수형을 반환

Get the current computed, pixel, width of the first matched element.
매치되는 첫번째 원소의 너비를 픽셀로 반환

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   function showWidth(ele, w) {
     $("div").text("The width for the " + ele +
                   " is " + w + "px.");
   }
   $("#getp").click(function () {
     showWidth("paragraph", $("p").width());
   });
   $("#getd").click(function () {
     showWidth("document", $(document).width());
   });
   $("#getw").click(function () {
     showWidth("window", $(window).width());
   });

  });
  </script>
  <style>
  body { background:yellow; }
  button { font-size:12px; margin:2px; }
  p { width:150px; border:1px red solid; }
  div { color:red; font-weight:bold;  }
  </style>
</head>
<body>
  <button id="getp">Get Paragraph Width</button>
  <button id="getd">Get Document Width</button>
  <button id="getw">Get Window Width</button>
  <div> </div>
  <p>
   Sample paragraph to test width
  </p>
</body>
</html>

8. width( val )  Returns: jQuery
width( val )  실행후 jQuery 객체를 반환

Set the CSS width of every matched element.
매치되는 모든 원소에 주어진 너비를 적용한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("div").one('click', function () {
     $(this).width(30)
            .css({cursor:"auto", "background-color":"blue"});
   });

  });
  </script>
  <style>
  div { width:70px; height:50px; float:left; margin:5px;
       background:red; cursor:pointer; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>



<Events>

1. ready( fn )  Returns: jQuery
ready( fn )  실행후 jQuery 객체를 반환

Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
문서가 준비가 되면 그 시점에 함수를 실행시킨다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").text("The DOM is now loaded and can be manipulated.");
  });
  </script>
  <style>p { color:red; }</style>
</head>
<body>
  <p>
  </p>
</body>
</html>


2. bind( type, data, fn )  Returns: jQuery
bind( type, data, fn )  실행후 jQuery 객체를 반환

Binds a handler to a particular event (like click) for each matched element.
지정된 이벤트가 일어날때까지 기다렷다가 함수 실행

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("p").bind("click", function(e){
     var str = "( " + e.pageX + ", " + e.pageY + " )";
     $("span").text("Click happened! " + str);
   });
   $("p").bind("dblclick", function(){
     $("span").text("Double-click happened in " + this.tagName);
   });

  });
  </script>
  <style>
  p { background:yellow; font-weight:bold; cursor:pointer;
     padding:5px; }
  span { color:red; }
  </style>
</head>
<body>
  <p>Click or double click here.</p>
  <span></span>
</body>
</html>


3. one( type, data, fn )  Returns: jQuery
one( type, data, fn )  실행후 jQuery 객체 반환

Binds a handler to a particular event to be executed once for each matched element.
지정된 이벤트가 일어날때까지 기다렷다가 한번만 실행

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   var n = 0;
   $("div").one("click", function(){
     var index = $("div").index(this);
     $(this).css({ borderStyle:"inset",
                   cursor:"auto" });
     $("p").text("Div at index #" + index + " clicked." +
                 "  That's " + ++n + " total clicks.");
   });

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:5px; float:left;
       background:green; border:10px outset;
       cursor:pointer; }
  p { color:red; margin:0; clear:left; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <p>Click a green square...</p>
</body>
</html>


4. trigger( type, data )  Returns: jQuery
trigger( type, data )  실행후 jQuery 객체 반환

Trigger a type of event on every matched element.
매치되는 모든 원소에 지정된 타입의 이벤트를 발생시킨다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("button:first").click(function () {
     update($("span:first"));
   });
   $("button:last").click(function () {
     $("button:first").trigger('click');

     update($("span:last"));
   });

   function update(j) {
     var n = parseInt(j.text(), 0);
     j.text(n + 1);
   }

  });
  </script>
  <style>
  button { margin:10px; }
  div { color:blue; font-weight:bold; }
  span { color:red; }
  </style>
</head>
<body>
  <button>Button #1</button>
  <button>Button #2</button>
  <div><span>0</span> button #1 clicks.</div>
  <div><span>0</span> button #2 clicks.</div>
</body>
</html>


5. triggerHandler( type, data )  Returns: jQuery
triggerHandler( type, data )  실행후 jQuery객체 반환

This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
잘은 모르겟지만 실제적인 행위는 하지 않고 그결과만 실행한다는 뜻인것 같음

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("#old").click(function(){
     $("input").trigger("focus");
   });
   $("#new").click(function(){
     $("input").triggerHandler("focus");
   });
   $("input").focus(function(){
     $("<span>Focused!</span>").appendTo("body").fadeOut(1000);
   });

  });
  </script>
 
</head>
<body>
  <button id="old">.trigger("focus")</button>
  <button id="new">.triggerHandler("focus")</button><br/><br/>
  <input type="text" value="To Be Focused"/>
</body>
</html>



6. unbind( type, data )  Returns: jQuery
unbind( type, data ), 실행후 jQuery 객체 반환

This does the opposite of bind, it removes bound events from each of the matched elements.
bind와 정반대의 역활을 하며 매치되는 모든 원소에 바운드 이벤트를 제거한다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   function aClick() {
     $("div").show().fadeOut("slow");
   }
   $("#bind").click(function () {
     // could use .bind('click', aClick) instead but for variety...
     $("#theone").click(aClick)
                 .text("Can Click!");
   });
   $("#unbind").click(function () {
     $("#theone").unbind('click', aClick)
                 .text("Does nothing...");
   });

  });
  </script>
  <style>
  button { margin:5px; }
  button#theone { color:red; background:yellow; }
  </style>
</head>
<body>
  <button id="theone">Does nothing...</button>
  <button id="bind">Bind Click</button>
  <button id="unbind">Unbind Click</button>
  <div style="display:none;">Click!</div>
</body>
</html>


7. hover( over, out )  Returns: jQuery
hover( over, out )  실행후 jQuery 객체를 반환

Simulates hovering (moving the mouse on, and off, an object). This is a custom method which provides an 'in' to a frequent task.
마우스 오버와 아웃시 행위를 지정할수 있다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("li").hover(
     function () {
       $(this).append($("<span> ***</span>"));
     },
     function () {
       $(this).find("span:last").remove();
     }
   );

  });
  </script>
  <style>
  ul { margin-left:20px; color:blue; }
  li { cursor:default; }
  span { color:red; }
  </style>
</head>
<body>
  <ul>
   <li>Milk</li>
   <li>Bread</li>
   <li>Chips</li>
   <li>Socks</li>
  </ul>
</body>


8. toggle( fn, fn )  Returns: jQuery
toggle( fn, fn )  실행후 jQuery 객체 반환

Toggle between two function calls every other click.
클릭시 두개의 함수를 반복적으로 실행

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("li").toggle(
     function () {
       $(this).css("list-style-type", "disc")
              .css("color", "blue");
     },
     function () {
       $(this).css({"list-style-type":"", "color":""});
     }
   );

  });
  </script>
  <style>
  ul { margin:10px; list-style:inside circle; font-weight:bold; }
  li { cursor:pointer; }
  </style>
</head>
<body>
  <ul>
   <li>Go to the store</li>
   <li>Pick up dinner</li>
   <li>Debug crash</li>
   <li>Take a jog</li>
  </ul>
</body>
</html>


9. blur( )  Returns: jQuery
blur( )  실행후 jQuery 객체 반환

Triggers the blur event of each matched element.


10. blur( fn )  Returns: jQuery
blur( fn )  실행후 jQuery 객체 반환

Bind a function to the blur event of each matched element.



11. change( )  Returns: jQuery
change( )  실행후 jQuery 객체 반환

Triggers the change event of each matched element.


12. change( fn )  Returns: jQuery
change( fn )  실행후 jQuery 객체 반환

Binds a function to the change event of each matched element.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("select").change(function () {
         var str = "";
         $("select option:selected").each(function () {
               str += $(this).text() + " ";
             });
         $("div").text(str);
       })
       .change();

  });
  </script>
  <style>
  div { color:red; }
  </style>
</head>
<body>
  <select name="sweets" multiple="multiple">
   <option>Chocolate</option>
   <option selected="selected">Candy</option>
   <option>Taffy</option>
   <option selected="selected">Carmel</option>
   <option>Fudge</option>
   <option>Cookie</option>
  </select>
  <div></div>
</body>
</html>


13. click( )  Returns: jQuery
click( )  실행후 jQuery 객체 반환

Triggers the click event of each matched element.


14. click( fn )  Returns: jQuery
click( fn )  실행후 jQuery 객체 반환

Binds a function to the click event of each matched element.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
  
   $("p").click(function () {
     $(this).slideUp();
   });
   $("p").hover(function () {
     $(this).addClass("hilite");
   }, function () {
     $(this).removeClass("hilite");
   });

  });
  </script>
  <style>
  p { color:red; margin:5px; cursor:pointer; }
  p.hilite { background:yellow; }
  </style>
</head>
<body>
  <p>First Paragraph</p>
  <p>Second Paragraph</p>
  <p>Yet one more Paragraph</p>
</body>
</html>


15. dblclick( )  Returns: jQuery
dblclick( )  실행후 jQuery 객체를 리턴

Triggers the dblclick event of each matched element.


16. dblclick( fn )  Returns: jQuery
dblclick( fn )  실행후 jQuery 객체를 리턴

Binds a function to the dblclick event of each matched element.


17. error( )  Returns: jQuery
Triggers the error event of each matched element.


18. error( fn )  Returns: jQuery
Binds a function to the error event of each matched element.



19. focus( )  Returns: jQuery
Triggers the focus event of each matched element.

20. focus( fn )  Returns: jQuery
Binds a function to the focus event of each matched element.



21. keydown( )  Returns: jQuery
Triggers the keydown event of each matched element.

22. keydown( fn )  Returns: jQuery
Bind a function to the keydown event of each matched element.



23. keypress( )  Returns: jQuery
Triggers the keypress event of each matched element.

24. keypress( fn )  Returns: jQuery
Binds a function to the keypress event of each matched element.



25. keyup( )  Returns: jQuery
Triggers the keyup event of each matched element.

26. keyup( fn )  Returns: jQuery
Bind a function to the keyup event of each matched element.


27. load( fn )  Returns: jQuery
Binds a function to the load event of each matched element.



28. mousedown( fn )  Returns: jQuery
Binds a function to the mousedown event of each matched element.


29. mousemove( fn )  Returns: jQuery
Bind a function to the mousemove event of each matched element.


30. mouseout( fn )  Returns: jQuery
Bind a function to the mouseout event of each matched element.


31. mouseover( fn )  Returns: jQuery
Bind a function to the mouseover event of each matched element.


32. mouseup( fn )  Returns: jQuery
Bind a function to the mouseup event of each matched element.


33. resize( fn )  Returns: jQuery
Bind a function to the resize event of each matched element.



34. scroll( fn )  Returns: jQuery
Bind a function to the scroll event of each matched element.



35. select( )  Returns: jQuery
Trigger the select event of each matched element.

36. select( fn )  Returns: jQuery
Bind a function to the select event of each matched element.



37. submit( )  Returns: jQuery
Trigger the submit event of each matched element.

38. submit( fn )  Returns: jQuery
Bind a function to the submit event of each matched element.



39. unload( fn )  Returns: jQuery
Binds a function to the unload event of each matched element.




<Effect>

1. show( )  Returns: jQuery
Displays each of the set of matched elements if they are hidden.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
   $("p").show()
  });
  </script>

</head>
<body>
  <p style="display:none">Hello</p>
</body>
</html>


2. show( speed, callback )  Returns: jQuery
Show all matched elements using a graceful animation and firing an optional callback after completion.
##A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("button").click(function () {
     $("p").show("slow");
   });

  });
  </script>
  <style>
  p { background:yellow; }
  </style>
</head>
<body>
  <button>Show it</button>
  <p style="display: none">Hello</p>
</body>
</html>


3. hide( )  Returns: jQuery
Hides each of the set of matched elements if they are shown.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("p").hide();
   $("a").click(function () {
     $(this).hide();
     return false;
   });

  });
  </script>

</head>
<body>
  <p>Hello</p>
  <a href="#">Click to hide me too</a>
  <p>Here is another paragraph</p>
</body>
</html>


4. hide( speed, callback )  Returns: jQuery
Hide all matched elements using a graceful animation and firing an optional callback after completion.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("button").click(function () {
     $("p").hide("slow");
   });

  });
  </script>
  <style>
  p { background:#dad; font-weight:bold; }
  </style>
</head>
<body>
  <button>Hide 'em</button>
  <p>Hiya</p>
  <p>Such interesting text, eh?</p>
</body>
</html>


5. toggle( )  Returns: jQuery
Toggles each of the set of matched elements.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("button").click(function () {
     $("p").toggle();
   });

  });
  </script>

</head>
<body>
  <button>Toggle</button>
  <p>Hello</p>
  <p style="display: none">Good Bye</p>
</body>
</html>


6. slideDown( speed, callback )  Returns: jQuery
Reveal all matched elements by adjusting their height and firing an optional callback after completion.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $(document.body).click(function () {
     if ($("div:first").is(":hidden")) {
       $("div").slideDown("slow");
     } else {
       $("div").hide();
     }
   });

  });
  </script>
  <style>
  div { background:#de9a44; margin:3px; width:80px;
       height:40px; display:none; float:left; }
  </style>
</head>
<body>
  Click me!
  <div></div>
  <div></div>
  <div></div>
</body>
</html>


7. slideUp( speed, callback )  Returns: jQuery
Hide all matched elements by adjusting their height and firing an optional callback after completion.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $(document.body).click(function () {
     if ($("div:first").is(":hidden")) {
       $("div").show("fast");
     } else {
       $("div").slideUp();
     }
   });

  });
  </script>
  <style>
  div { background:#3d9a44; margin:3px; width:80px;
       height:40px; float:left; }
  </style>
</head>
<body>
  Click me!
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>




8. slideToggle( speed, callback )  Returns: jQuery
Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("button").click(function () {
     $("p").slideToggle("slow");
   });

  });
  </script>
  <style>
  p { width:400px; }
  </style>
</head>
<body>
  <button>Toggle</button>
  <p>
   This is the paragraph to end all paragraphs.  You
   should feel <em>lucky</em> to have seen such a paragraph in
   your life.  Congratulations!
  </p>
</body>
</html>


9. fadeIn( speed, callback )  Returns: jQuery
Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $(document.body).click(function () {
     $("div:hidden:first").fadeIn("slow");
   });

  });
  </script>
  <style>
  span { color:red; cursor:pointer; }
  div { margin:3px; width:80px; display:none;
       height:80px; float:left; }
  div#one { background:#f00; }
  div#two { background:#0f0; }
  div#three { background:#00f; }
  </style>
</head>
<body>
  <span>Click here...</span>
  <div id="one"></div>
  <div id="two"></div>
  <div id="three"></div>
</body>
</html>



10. fadeOut( speed, callback )  Returns: jQuery
Fade out all matched elements by adjusting their opacity and firing an optional callback after completion.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("p").click(function () {
     $("p").fadeOut("slow");
   });

  });
  </script>
  <style>
  p { font-size:150%; cursor:pointer; }
  </style>
</head>
<body>
  <p>
   If you click on this paragraph
   you'll see it just fade away.
  </p>
</body>
</html>


11. fadeTo( speed, opacity, callback )  Returns: jQuery
Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("p:first").click(function () {
     $(this).fadeTo("slow", 0.33);
   });

  });
  </script>

</head>
<body>
  <p>
   Click this paragraph to see it fade.
  </p>
  <p>
   Compare to this one that won't fade.
  </p>
</body>
</html>


12. animate( params, duration, easing, callback )  Returns: jQuery
A function for making your own, custom animations.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("#right").click(function(){
     $(".block").animate({"left": "+=50px"}, "slow");
   });

   $("#left").click(function(){
     $(".block").animate({"left": "-=50px"}, "slow");
   });

  });
  </script>
  <style>
  div {
   position:absolute;
   background-color:#abc;
   left:50px;
   width:90px;
   height:90px;
   margin:5px;
  }
  </style>
</head>
<body>
  <button id="left">≪</button> <button id="right">≫</button>
<div class="block"></div>

</body>
</html>


13. animate( params, options )  Returns: jQuery
A function for making your own, custom animations.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   // Using multiple unit types within one animation.
   $("#go").click(function(){
     $("#block").animate({
       width: "70%",
       opacity: 0.4,
       marginLeft: "0.6in",
       fontSize: "3em",
       borderWidth: "10px"
     }, 1500 );
   });

  });
  </script>
  <style>
  div {
   background-color:#bca;
   width:100px;
   border:1px solid green;
  }
  </style>
</head>
<body>
  <button id="go">≫ Run</button>
  <div id="block">Hello!</div>
</body>
</html>


14. stop( )  Returns: jQuery
Stops all the currently running animations on all the specified elements.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   // Start animation
   $("#go").click(function(){
     $(".block").animate({left: '+=100px'}, 2000);
   });

   // Stop animation when button is clicked
   $("#stop").click(function(){
     $(".block").stop();
   });

   // Start animation in the opposite direction
   $("#back").click(function(){
     $(".block").animate({left: '-=100px'}, 2000);
   });

  });
  </script>
  <style>div {
   position: absolute;
   background-color: #abc;
   left: 0px;
   top:30px;
   width: 60px;
   height: 60px;
   margin: 5px;
  }
  </style>
</head>
<body>
  <button id="go">Go</button>
  <button id="stop">STOP!</button>
  <button id="back">Back</button>
  <div class="block"></div>
</body>
</html>


15. queue( )  Returns: Array<Function>
Returns a reference to the first element's queue (which is an array of functions).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("#show").click(function () {
     var n = $("div").queue("fx");
     $("span").text("Queue length is: " + n.length);
   });
   function runIt() {
     $("div").show("slow");
     $("div").animate({left:'+=200'},2000);
     $("div").slideToggle(1000);
     $("div").slideToggle("fast");
     $("div").animate({left:'-=200'},1500);
     $("div").hide("slow");
     $("div").show(1200);
     $("div").slideUp("normal", runIt);
   }
   runIt();

  });
  </script>
  <style>
  div { margin:3px; width:40px; height:40px;
       position:absolute; left:0px; top:30px;
       background:green; display:none; }
  div.newcolor { background:blue; }
  span { color:red; }
  </style>
</head>
<body>
  <button id="show">Show Length of Queue</button>
  <span></span>
  <div></div>
</body>
</html>


16. queue( callback )
Adds a new function, to be executed, onto the end of the queue of all matched elements.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $(document.body).click(function () {
     $("div").show("slow");
     $("div").animate({left:'+=200'},2000);
     $("div").queue(function () {
       $(this).addClass("newcolor");
       $(this).dequeue();
     });
     $("div").animate({left:'-=200'},500);
     $("div").queue(function () {
       $(this).removeClass("newcolor");
       $(this).dequeue();
     });
     $("div").slideUp();
   });

  });
  </script>
  <style>
  div { margin:3px; width:40px; height:40px;
       position:absolute; left:0px; top:30px;
       background:green; display:none; }
  div.newcolor { background:blue; }
  </style>
</head>
<body>
  Click here...
  <div></div>
</body>
</html>


17. queue( queue )
Replaces the queue of all matched element with this new queue (the array of functions).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("#start").click(function () {
     $("div").show("slow");
     $("div").animate({left:'+=200'},5000);
     $("div").queue(function () {
       $(this).addClass("newcolor");
       $(this).dequeue();
     });
     $("div").animate({left:'-=200'},1500);
     $("div").queue(function () {
       $(this).removeClass("newcolor");
       $(this).dequeue();
     });
     $("div").slideUp();
   });
   $("#stop").click(function () {
     $("div").queue("fx", []);
     $("div").stop();
   });

  });
  </script>
  <style>
  div { margin:3px; width:40px; height:40px;
       position:absolute; left:0px; top:30px;
       background:green; display:none; }
  div.newcolor { background:blue; }
  </style>
</head>
<body>
  <button id="start">Start</button>
  <button id="stop">Stop</button>
  <div></div>
</body>
</html>


18. dequeue( )  Returns: jQuery
Removes a queued function from the front of the queue and executes it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){

   $("button").click(function () {
     $("div").animate({left:'+=200px'}, 2000);
     $("div").animate({top:'0px'}, 600);
     $("div").queue(function () {
       $(this).toggleClass("red");
       $(this).dequeue();
     });
     $("div").animate({left:'10px', top:'30px'}, 700);
   });

  });
  </script>
  <style>
  div { margin:3px; width:50px; position:absolute;
       height:50px; left:10px; top:30px;
       background-color:yellow; }
  div.red { background-color:red; }
  </style>
</head>
<body>
  <button>Start</button>
  <div></div>
</body>
</html>

Posted by 1010
반응형
이전에 파이어준님의 포스팅 에서 보고는 담에는 써야지 하다가 이번에야 써봤다. 쉽게 말하면 자바스크립트 프레임워크를 구글이 제공 해서 자신의 사이트에 올리지 않고 구글에서 끌어다가 쓸 수 있게 한다. 머 이건데... 회사에서는 쓸 일 있을지 모르겠고 블로그에서 예제파일 돌릴려고 몇개 올려두기는 했는데 버전도 계속 바뀌고 그래서 신경이 쓰였는데 이 서비스는 내가 써먹기는 딱인듯 하다. ㅋ 그래서 바로 전의 포스팅을 하면서 한번 써봤다. 잘된다.(당연하지. ㅡ..ㅡ)

파이어준님의 포스팅에도 나와있긴 하지만 다시 정리하자면
제공하는 라이브러리는 jQuery , prototype , script.aculo.us , mootools , dojo 이다.(2008년 8월 1일 현재...) - 2개씩 적혀 있는 것은 위의것은 압축된(compressed) 버전이고 아래쪽은 압축되지 않은 버전이다.)

jQuery (1.2.3, 1.2.6 지원)
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>   
  2. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>   


prototype (1.6.0.2 지원)
  1. <script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script>   


script.aculo.us (1.8.1 지원)
  1. <script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.1/scriptaculous.js "></script>   


mootools (1.11 지원)
  1. <script src="http://ajax.googleapis.com/ajax/libs/mootools/1.11/mootools.js"></script>   
  2. <script src="http://ajax.googleapis.com/ajax/libs/mootools/1.11/mootools.js"></script>   


dojo (1.1.1 지원)
  1. <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.1.1/dojo/dojo.xd.js "></script>   
  2. <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.1.1/dojo/dojo.xd.js.uncompressed.js"></script> 


머 사용법이고 말고 할것도 없다. 그냥 script 인클루드의 링크를 구글로 건거다. ㅋㅋ 구글 API써서 하는 방법도 있지만 평소에도 이런식이 익숙하니까 이게 더 편한 것 같다. 이렇게 블로그에 올리거나 잠시 테스트할 때 프레임웍 불러내는게 은근 귀찮은데 이렇게 쓰니까 참 편하다.



그냥 구글이 갔다 쓸수만 있게 했겠는가? ㅋ Ajaxian의 포스트 에 따르면 다음과 같은 장점이 있다고 한다.

  • 개발자가 아무짓도 안해도 캐싱이 잘 된다.
  • Gzip으로 동작한다.
  • 최소화된 버전으로 제공할 수 있다.
  • 세계곳곳의 CDN을 통해서 구글이 파일을 호스팅하기 때문에 사용자가 빨리 받을 수 있다.
  • 서버가 빠르다.
  • 같은 URL을 사용하기 때문에 구글의 인프라가 커지면 사용자가 당신의 어플리케이션에 처음왔을 때 이미 프레임워크가 로드되어 있을수도 있다.
  • 당신이 보내고 받는 헤더관련 미묘한 성능 및 보안 이슈가 해결된다. 당신이 특별한 도메인(구글말고)을 사용한 이래고 쿠기가 없거나 다른 장황한 헤더가 보내질 것이므로 귀중한 바이트를 아낄수 있다.
개발하는 사이트에서 자신의 사이트에 라이브러리가 없는게 좀 신경쓰일 수도 있지만 많은 장점이 있는데도 굳이 안 쓸 이유도 없을것 같다. 나야 개인적으로만 쓰겠지만.. ㅎㅎㅎㅎ



위에처럼 직접 인클루드하는 방법 외에도 Google AJAX API Loader를 이용해서도 라이브러리 파일을 인클루드 할 수 있다.  구글과으 매쉬업을 위해서 구글 api를 사용한다면 google.load()방식이 더욱 유용할 것이다.

  1. <script src="http://www.google.com/jsapi"></script> 
  2. <script type="text/javascript"> 
  3.     // jQuery 압축, 비압축  
  4.     google.load("jquery", "1.2.6");  
  5.     google.load("jquery", "1.2", {uncompressed:true});  
  6.  
  7.     // prototype, scriptaculous  
  8.     google.load("prototype", "1.6.0.2");  
  9.     google.load("scriptaculous", "1.8.1");  
  10.  
  11.     // mootools 압축, 비압축  
  12.     google.load("mootools", "1.11");  
  13.     google.load("mootools", "1.11", {uncompressed:true});  
  14.  
  15.     // dojo 압축, 비압축  
  16.     google.load("dojo", "1.1.1");  
  17.     google.load("dojo", "1.1.1", {uncompressed:true});  
  18. </script> 




마지막으로 Google AJAX Libraires API에 대한 설명 영상

Posted by 1010
반응형

[ExtJs] 튜토리얼 1

  2008/07/17 16:44:31 초급 프로젝트 만들기

 1단계 :

extjs001.jpg다음과 같이 ExtJS 라이브러리를 사용할 때는


[파일명].css -> 디자인 정의

[파일명].html -> ExtJs 라이브러리를 사용하기 위해 스크립트로 선언해줘야 한다.

[파일명].js  -> 실제 구동되는 내용이 들어간다.


세개의 파일을 만드는게 기본 구조이다.


본 화면은 Aptana 스튜디오 화면이다. 개발을 할때는 FireFox에 FireBug 플러그인을 설치하여

콘솔로 테스트를 해보는걸 권장한다.



2단계 :

테스트용이기 때문에 applayout.js 에는 아무 내용이 들어있지 않다. 콘솔 테스트 시에는 FireBug를 이용한다.

FireBug를 실행할 때는 FireFox 에서 F12 키를 눌러주면 된다.

테스트 서버 URL : http://aha.chonbuk.ac.kr/extJsTest/widget/applayout.html

  1. applayout.css
  2. body {
       font-family:verdana,tahoma,helvetica;
       padding:0px;
       padding-top:0px;
       font-size:13px;
       background-color:#fff !important;
    }

  1.  applayout.html
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
     <head>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
      <title>Untitled Document</title>
     
      <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css" />
  3.   <!-- GC -->
      <!-- LIBS -->    
         <script type="text/javascript" src="lib/ext/adapter/yui/yui-utilities.js"></script>
         <script type="text/javascript" src="lib/ext/adapter/yui/ext-yui-adapter.js"></script>
      <!-- ENDLIBS -->
         <script type="text/javascript" src="lib/ext/ext-all-debug.js"></script>
     
      <!-- Common Styles for the examples -->
      <link rel="stylesheet" type="text/css" href="applayout.css" />
     </head>
     <body>
     </body>
    </html>

3단계:

FireFox에서 FireBug의 콘솔을 이용하여 테스트를 해볼 수 있다.

  1. Ext.get(document.body).update('<div id="test">테스트</div>'); <- body 태그 안에 내용을 갱신한다.

extjs002.jpg 


4단계: 작업 패널을 만들어 본다.

  1. Ext.get(document.body).update('<div id="test">테스트</div>');
  2. new Ext.Panel({              //<- 다음과 같이 윈도우 하나를 띄워준다.
       renderTo: 'test',            //<- 윈도우를 그릴 레이어 id 를 적어준다.
       width: '200px',               //<- 윈도우의 가로 사이즈를 나타낸다.
       title: 'My Title',               //<- 프레임 타이틀 이름을 표시한다.
       html: 'My HTML content'   //<- 실제적인 컨텐츠가 들어가는 부분이다.
    });

 extjs003.jpg


5단계 : 작업 패널의 확장 속성을 주어보자!

파란색 상자로 쳐진 부분이 새로 추가한 내용이다. 작업화면에 다음과 같이 확장 가능한 화면이 표시된다.

 extjs004(1).jpg


6단계 : API 에서 필요로 하는 탭 기능으로 워크 스페이스 구현할 예제를 한번 만들어보았다

다음과 같이 Ext.TabPanel() 을 이용하면 다음과 같은 화면이 그려지게 된다. 생각보다 깔끔하게 잘 나온다.

extjs005.jpg 


7단계 : 탭패널을 이용하여 워크스페이스 만들어보기

extjs006.jpg 탭 워크스페이스 예제의 구성 파일은다음과 같다

loripsum.html : 새로운 탭이 만들어질때 씌여지는 컨텐츠가 들어간다. 우선 아무 내용이나 집어넣었다.

sample0.html, sample1.html : 탭뷰가 갱신되는걸 표시하기 위한 컨텐츠, 우선 아무 내용이나

tab_actions.js : 탭 워크스페이스를 구현하는 자바스크립트 소스

tabLayout.html : 탭 워크스페이스의 레이아웃
















 탭 워크스페이스를 구현한 그림이다.

워크스페이스를 갱신하면 원래 있던 내용이 바뀐다.

새로운 워크스페이스를 추가하면 탭 워크스페이스가 늘어난다.

테스트 URL : http://aha.chonbuk.ac.kr/extJsTest/widget/tabLayout.html


extjs007(1).jpg 

  1. tabLayout.html
  2. <html>
    <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>TabPanel Tutorial</title>
     <!-- Ext CSS and Libs -->
     <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css" />
     <script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script>
     <script type="text/javascript" src="lib/ext/ext-all.js"></script>
     
     <!-- Custom CSS and Libs -->
     <script type="text/javascript" src="./tab_actions.js"></script>
     <link rel="stylesheet" type="text/css" href="shared/share.css" />
     <style>
     #actions li {
      margin:.3em;
     }
     #actions li a {
      color:#666688;
      text-decoration:none;
     }
     </style>
    </head>
    <body>
  3. <ul id="actions" class="x-hidden">
     <li>
      <a id="use" href="#">워크스페이스 갱신</a>
     </li>
     <li>
      <a id="create" href="#">새로운 워크스페이스 추가</a>
     </li>
    </ul>
     
    <div id="tabs"></div>
    </body>
    </html>

  1. tab_action.js
  2.  Ext.onReady(function(){
          // Menu containing actions
           var tabActions = new Ext.Panel({
            frame:true,
            title: '워크스페이스 관리',
            collapsible:true,
            contentEl:'actions',    
            titleCollapse: true
        });
     
        // Parent Panel to hold actions menu
        var actionPanel = new Ext.Panel({
            id:'action-panel',
            region:'east',                     //<-자바의 레이아웃 구분과 같다. north, west, east, south, center
            split:true,
            collapsible: true,
            collapseMode: 'mini',
            width:200,
            minWidth: 150,
            border: false,
            baseCls:'x-plain',
            items: [tabActions]         //<-앞 서 만든 워크스페이스 관리 프레임을 패널에 집어 넣는다.
        });
     
        // Main (Tabbed) Panel
        var tabPanel = new Ext.TabPanel({
            region:'center',
            deferredRender:false,
            autoScroll: true,
  3.         enableTabScroll:true,     // <- 탭 이 화면에 다 표시 안될경우 좌우 스크롤 할 수 있게 해준다.
            margins:'0 4 4 0',
            activeTab:0,
            items:[{
                id:'tab1',
                contentEl:'tabs',
                title: '워크스페이스',
                closable:true,
                autoScroll:true
            }]
        });
       
        // Configure viewport
        viewport = new Ext.Viewport({
               layout:'border',
               items:[actionPanel,tabPanel]
        });
       
         // Adds tab to center panel
        function addTab(tabTitle, targetUrl){
            tabPanel.add({
                  title: tabTitle,
                  iconCls: 'tabs',
                  autoLoad: {url: targetUrl, callback: this.initSearch, scope: this},
                  closable:true
           }).show();
        }
     
        // Update the contents of a tab if it exists, otherwise create a new one
        function updateTab(tabId,title, url) {
         var tab = tabPanel.getItem(tabId);
         if(tab){
          tab.getUpdater().update(url);
          tab.setTitle(title);
         }else{
          tab = addTab(title,url);
         }
         tabPanel.setActiveTab(tab);
        }
     
        // Map link ids to functions
        var count = 0;
        var tabcount = 0;
        var actions = {
         'create' : function(){
          addTab('새 워크스페이스'+tabcount,'loripsum.html');
          tabcount++;
         },
         'use' : function(){
          // Toggle between sample pages
          updateTab('tab1','워크스페이스 갱신 ' + count + ' 회','sample'+(count%2)+'.html');
          count++;      
         }
        };
     
        function doAction(e, t){
         e.stopEvent();
         actions[t.id]();
        }
     
        // This must come after the viewport setup, so the body has been initialized
       
        actionPanel.body.on('mousedown', doAction, null, {delegate:'a'});          
    });




















Posted by 1010
반응형
[Source Link] 
Author: Brian Moeskau (변역:김재형)
Published: Novermber 1, 2007
Ext Version: 2.0
Last Modified: 2008.2.17 14:55
Summary: 2008.10.9 16:40 (Roundworld)


ExtStart.js

Ext.onReady(function(){
    alert("Congratulations! You have Ext configured correctly!");
});

Ext.onReady는 반드시 가장 처음으로 호출되는 메소드입니다. 모든 DOM의 로딩이 완료되어야 이 메소드가 자동으로 호출되므로 이 메소드 내부의 코드는 페이지 내 모든 엘리먼트에 접근이 가능합니다.


- Element: Ext 심장

var myDiv = document.getElementById('myDiv');

이 코드는 잘 실행되긴 하지만 여기서 반환되는 객체는(DOM node) 쓰기 쉽지는 않고 기능이 강력하지 않습니다. 반환된 node를 유용하게 사용하려면 많은 추가코드를 작성해야 합니다. 게다기 브라우저 별 호환성에 대해서도 고려를 해야하므로 짜증 만땅이라 할 수 있지요. (변역이 참 재밌습니다.)

이제 Ext.Element 객체를 살펴봅시다. 정말 Ext의 심장과도 같은 이 객체는 엘리먼트에 접근하거나 기능을 실행할고 할때 필요합니다.  Element API는 Ext 라이브러리에 입문하려고 할때 기초가 되며 여러분이 Ext에서 오직 하나의 클래스만 배울 시간만 가지고 있다면 Element를 선택하세요!

앞의 예제 코드에 대응되는 Ext Element로 ID를 얻어내는 코드는 아래와 같습니다.

Ext.onReady(function() {
    var myDiv = Ext.get('myDiv');
});

이제 Element 객체로 다시 돌아가서... 왜 흥미를 가져야 할까요?

1.Element 클래스는 대부분의 기존 DOM 매소드와 프로퍼티를 포함하고 있는데, 이로 인해 편리성, 통합성, 브라우저간 호환성이 있는 DOM 인터페이스를 얻게 됩니다.

2.Element.get() 메소드는 내부 캐쉬를 사용하며 따라서 동일한 객체를 반복해서 호출할 때 겁나(^^) 빠른 속도를 얻어 올수 있습니다.

3.브라우저간 호환성 문제가 없는 Element 메소드들을 통해서 DOM 노드에 대한 대부분의 작업이 수행됩니다.


- DOM node들 선택하기

종종 DOM 노드를 ID로 선택하는게 불가능 하거나 비효율적일 경우가 있습니다. 엘리먼트에 ID가 설정되어 있지 않거나 설정된 ID를 모를때, 혹은 ID로 참조할 요소가 너무 많을 경우에는 여러분은 엘리먼트에 설정된 어떤 프로퍼티 값이나 설정된 CSS 클래스명으로 선택한다던가하는 먼가 다른 방법이 필요할 겁니다. 이런 경우를 위해서 Ext에서는 DomQuery라고 불리는 극악 강력한(--;) DOM 선택 라이브러리를 제공합니다.

// Hightlights every paragraph
Ext.select('p').hightlight();   

예제는 Element.select를 아주 손쉽게 사용하는 방법을 보여줍니다. 여기서 반환되는 객체는 CompositeElement로 Element 인터페이스를 통하여 내부 엘리먼트에 접근할 수 있게 해줍니다. 이것은 반복문과 개별접근이 없이 Element.select로 손쉽게 모든 엘리먼트의 인스턴스를 리턴 받을수 있게 해줍니다.

DomQuery는 W3C CSS3 DOM selector의 기본 Xpath 그리고, HTML 프로퍼티를 포함하는 폭넓은 선택 옵션을 지원합니다.


- 이벤트 응답

지금까지 예제에서는 우리가 작성한 코드는 모두 onReady 함수 내에 직접 작성되었습니다. 이것이 뜻하는 바는 이것들은 항상 페이지의 로드가 완료된 즉시 실행이 된다는 것입니다. 이것은 우리에게 많은 제어권을 주지 못합니다. 여러분은 제어를 위해 코드가 특정 상황 혹은 이벤트에 응답하게끔 하고 싶을 겁니다. 이것을 하려면 이벤트 처리를 하는 함수를 이벤트 핸들러로 정의 해야합니다.

간단한 예제부터 시작하면 ExtStart.js를 열어서 아래와 같이 수정합니다.

Ext.onReady(function() {
    Ext.get('myButton').on('click', function() {
        alert("You clicked the button");
    });
});

코드는 아직까지 페이지가 로드 완료이후에 실행되지만 한가지 다른점은 함수내에 alert()이 선언되어 있는데 즉시 실행되지 않습니다. 이 부분은 버튼의 클릭 이벤트에 대한 "핸들러"로 지정되어 있기 때문입니다.

놀라지 마세요.(^^) Element.select는 같은 기능을 제공하지만 한번에 모든 요소 그룹을 가져올수 있습니다. 예를 들어, 우리 태스트 페이지 내에 모든 문단을 클릭 했을때 메시지를 보여주려면 다음과 같이 해봅시다.

Ext.onReady(function(){
    Ext.select('p').on('click',function(){
        alert("You clicked a paragraph");
    });
});

여기 두개의 예제 내에서 이벤트 처리함수는 함수명이 없이 단순히 인라인(inline)으로 선언되어 있습니다. 이러한 종류의 함수를 "익명함수(anonymous function)"라고 하는데 물론 이름이 있는 함수도 이벤트 처리용으로 할당 할 수 있습니다. 아래 예제 코드는 앞서의 예제와 동일한 기능을 수행합니다.

Ext.onReady(function(){
    var paragraphClicked = function(){
        alert("U clicked a paragraph");
    }
    Ext.select('p').on('click', paragraphClicked);
});

여기까지 우리는 이벤트가 발생되었을때 일반적인 처리를 하는 방법을 살펴 보았습니다. 하지만 이벤트가 발생한 엘리먼트 자체에 대한 어떤 액션을 실행하려고 할때, 해당 엘리먼트를 어떻게 알아 낼 수 있을까요?

물론 간단히 찾아 낼 수 있습니다.

Element.on 메소드는 이벤트 핸들링 함수에 3개의 완전 유용한 파라메터를 전달합니다.(여기서는 첫번째 1개만 살펴봅니다. 나머지는 API문서를 참조하세요.) 앞서 예제에서는 핸들링 함수에 파라메터가 생략되어 있습니다. 하지만 조금만 바꿔서 부가적인 기능을 추가시킬수 있습니다. 첫번째(가장 중요한) 파라메터는 발생된 이벤트입니다. 이것은 사실 Ext 이벤트 객체인데, 표준 브라우저 이벤트 보다 브라우저간 호환성이 있고 더욱 많은 정보를 제공합니다. 예를들어, 아래처럼 가단한 코드 추가만으로 이벤트의 traget으로 설정된 DOM 노드를 구할수 있습니다.

Ext.onReady(function() {
    var paragraphClicked = function(e){
        Ext.get(e.target).highlight();
    }
    Ext.select('p').on('click', paragraphClicked);
});

target이 DOM 노드라는 것을 기억하시고, 이제 이벤트가 발생된 엘리먼트를 구해서 원하는 액션을 수행할 수 있게 되었습니다. 예제를 실행해보면 모든 문단에 하이라이트가 되는 것을 볼수 있습니다.


- 위젯 사용하기

Ext는 지금까지 설명한 코어 자바스크립트 라이브러리 외에 추가적으로 풍부한 자바스크립트 UI위젯들을 제공합니다. 본 문서에서 설명하기에는 분량이 너무 많으므로 주로 사용되는 몇가지를 얼마나 쉽게 사용할수 있는지 알아보겠습니다.


1.MessageBox

지루한 "Hello World" 메시지 박스 띄우기 대신 다른것을 해 봅시다. 우리는 이전에 섹션에서는 각각 문단을 클릭했을때 하이라이트가 되는 코드를 작성했는데 이번에는 클릭했을때 나타나는 메시지 박스 안에 문장의 글이 보이게끔 수정해봅시다. 아래 paragraphClicked 함수를 고쳐봅시다.

Ext.get(e.target).highlight();

var paragraph = Ext.get(e.target);
paragraph.highlight();

Ext.MessageBox.show({
    title: 'Paragraph Clicked',
    msg: paragraph.dom.innerHTML,
    width: 400,
    buttons: Ext.MessageBox.OK,
    animEl: paragraph
});

여기서 다루어 볼만한 가치가 있는 몇가지 새로운 컵셉이 눈에 띠는군요. 첫라인에서 paragraph라는 이름으로 지역변수(전역변수 아닌가요? --;)를 생성 했으며 클릭이 발생한 DOM 노드의 엘리먼트 참조를 가지고 있게 했습니다.(이번에는 오직 <p> 태그들만 클릭 이벤트와 연계되므로 항상 입력되는 것을 알 수 있습니다.)

왜 이렇게 해야 할까요? 우리는 하이라이트 시키기 위한 엘리먼트의 참조가 필요하며 메시지박스를 위한 인자로 동일한 엘리먼트를 필요하기 때문입니다. 일반적으로 동일한 값 또는 객체 참조를 얻기 위해 동일한 함수를 여러번 호출하는 것은 나쁜습관(--;)이므로 지역 변수에 할당하여 재사용합니다. 이렇게 하면 우리는 착한 객체지향 개발자가 되는 겁니다!

이제 메시지박스호출 부분을 살펴봅시다. 또 다른 새로운 컨셉이 보이는데 단순히 메소드에 인자 리스트를 전달하는 것처럼 보이지만 자세히 살펴보면 매우 특이한 문법이 보일겁니다. 사실 MessageBox.show()에는 오직 하나의 인자만 전달되고 있는데 프로터피와 값의 집합을 담고 있는 객체 문자열(literal)입니다. 자바스크립트에서 객체 문자열은 이름/값 프로퍼티 리스트를 {}로 감싸서 언제든지 동적으로 생성시킬수 있습니다. 형식은 [프로퍼티 이름]:[프로퍼티 값] 으로 표기하며 이 패턴은 Ext 곳곳에서 널리 사용되기 때문에 금방 익술해질겁니다.

왜 객체 문자열(literal)을 사용하냐구요? 가장 큰 이유는 유연성입니다. 객체 문자열(literal)을 사용하면 아무때나 프로퍼티나 추가/삭제 되거나 순서가 변경되더라도 메소드의 시그니쳐(인자의 개수와 타입) 예를 들어 foo.action 이라는 가상의 메소드가 있다고 하고 네개의 옵션인자가 있다고 가정합니다. 그런데 오직 하나만 전달하는 상황이라면 코드를 다음과 같이 작성해야겠지요.

foo.action(null,null,null,'hello')

그러나 객체 문자열(literal)을 사용하게 된다면 다음과 같이 하면 됩니다.

foo.action(
    param4: 'hello'
})
 
무척 사용하기 쉽고 가독성도 더 좋습니다.


2.Grid

그리드는 Ext의 가장 인기있는 위젯 중 하나인데 사람들이 첫번째로 보고 싶어하는 것이기도 합니다. 자 이제 기초적인 그리드를 만들고 실행시키는 것이 얼마나 쉬운지 살펴보겠습니다. ExtStart.js 파일을 열어서 아래와 같이 코드를 수정해봅시다.

Ext.onReady(function() {
    var myData = [
                    ['Apple',29.89,0.24,0.81, '9/1 12:00am'],
                    ['Ext',83.81,0.28,0.34,'9/12 12:00am'],
                    ['Google',52.55,0.01,0.02,'7/4 1200am'],
                    ['Microsoft',52.55,0.01,0.02,'7/4 12:00am'],
                    ['Yahoo!',29.01,0.42,1.47,'5/22 12:00am']
    ];

    var myReader = new Ext.data.ArrayReader({}, [
                    {name: 'company'},
                    {name: 'price', type: 'float'},
                    {name: 'change', type: 'float'},
                    {name: 'pctChange', type: 'float'},
                    {name: 'lastChange', type: 'date', daeFormat: 'n/j h:ia'}
    ]);

    var grid = new Ext.grid.GridPanel({
                   store: new Ext.data.Store({
                            data: myData,
                            reader: myReader
                   }),
                   columns: [
                                 {header: "Company", width: 120, sortable: true, dataIndex: 'company'},
                                 {header: "Price", width: 90, sortable: true, dataIndex: 'price'},
                                 {header: "Change", width: 90, sortable: true, dataIndex: 'change'},
                                 {header: "% Change", width: 90, sortable: true, dataIndex: 'pctChange'},
                                 {header: "Last Updated", width:120, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
                  ],
                  viewConfig: {
                                 forceFit: true
                  },
                  renderTo: 'content',
                  title: 'My First Grid',
                  width: 500,
                  frame: true
});

grid.getSelectionModel().selectFirstRow();                  
});                                

코드가 길어 보이지만 실제로는 오직 4 line Code 뿐입니다. (태스트 데이타를 제외하면 3 Line Code)!

1.첫라인은 그리드에 보여줄 태스트 데이타를 생성, 실제로는 DB에서 데이타를 가져오겠죠.
2.다음은 데이터 리더를 생성하였는데 그리드 내 데이터 스토어에 담기 위해 데이터를 어떻게 읽어 들이고 레코드로 변환할지 설정합니다. 다양한 데이터 타입을 위한 각각의 리더 클래스가 있습니다.
3.다음으로 그리드 위젯을 생성하는데 아래와 같은 설정 값들을 전달합니다.
- 새로운 데이타 스토어, 생성한 태스트 데이터와 리더가 설정되어 있습니다.
- Columns에 칼럼 모델 정의를 합니다.
- 추가옵션으로 그리드의 기능 설정을 할수 있습니다.
4.마지막으로 SelectionModel을 사용해 첫번째 행을 하이라이트 시킵니다.

무척 간단하지요? (--;;) 잘 되었다면 아래와 같이 보일 겁니다.



물론 이런 코드를 가지고 자세한 부분까지 이해할 수는 없습니다. 이 예제의 목적은 풍부하고 시각적으로 복잡한 사용자 인터페이스 컴포넌트를 최소한의 코드만으로 작성할 수 있다는 것을 보여주는데 있습니다.

자세한 내용은 독자들의 숙제로 남깁니다. 그리드를 배우는데 도움이 되는 많은 내용들이 interactive grid damosGridPanel API documentation 에 포함되어 있습니다.



3.그리고 다른 것들...

지금 우리가 살펴본 것은 빙산의 일각(--;)에 불가합니다. Ext에 있는 수십개의 UI위젯들이 있습니다. 자동 페이지 레이아웃, 탭, 메뉴, 다이어로그, 트리뷰 등등. interactive examples 에서 모두 살펴보시기 바랍니다.



- Ajax 사용하기

페이지를 만들고 자바스크립트로 상호작용하는 것을 알게 되었습니다. 이제 여러분은 서버의 데이터베이스에서 가져오거나 저장하는 것과 같은 원격 서버에서 데이터를 가져오는 방법을 알고 싶을 겁니다. 자바스크립트를 이용하며 비동기적으로 페이지 리로딩 없이 처리하는 방식은 Ajax 라고 알려져 있는데 Ext는 Ajax를 지원합니다. 예를 들어 사용자와의 상호작용을 처리하여 서버에 비동기로 전송하고 응답하는 UI의 엘리먼트를 갱신하는 것인데 여기에 택스트 입력 박스, 버트, 메시지를 표시하기 위한 div를 포함하고 있는 간단한 HTML 폼으로 구성된 예제를 살펴봅시다.

ExtStart.html
<div>
    Name: <input type="text" id="name" />
    <input type="button" id="okButton" value="OK" />
</div>
<div id="msg"></div>

ExtStart.js
Ext.onReady(function(){
    Ext.get('okButton').on('click', function() {
        var msg = Ext.get('msg');
        msg.load({
                        url: 'ajax-example.php', //<-- change if nessary
                        params: 'name=' + Ext.get('name').dom.value,
                        text: 'Updating...'
        });
        msg.show();
    });
});

아마도 일반적인 패턴은 지금과 비슷하게 시작할겁니다! 이 코드는 okButton을 Element 객체로 래핑시키고 버튼 클릭 이벤트를 처리하는 익명함수로 연결시키고 있습니다. 클릭 핸들러 내에서는 Updater라고 불리우는 특별한 내부 클래스를 사용하는데 이 클래스는 손쉽게 Ajax 응답을 주고 받고 다른 엘리먼트를 갱신합니다.

Updater는 직접 호출하거나 여기에서처럼 갱신을 원하는 Element(여기서는 'msg' div)에 Element.load를 사용하여 접근하게 되는데 Element.load가 호출되었을 때 서버 측의 응답이 자동으로 Element의 innerHTML로 변경됩니다. 그리고 서버에서 응답을 처리할 URL과 인자값(여기서는 'name'필드의 값을 전달) 그리고 요철 처리 중간에 엘리먼트의 innerHTML에 표시할 메시지를 전달하고, Msg div(디폴트 값이 hidden으로 되어있음)가 보이게하면 됩니다.

물론 Ext 내 다른 부분들처럼 Updater에 많은 옵션들이 제공 되고 있으며 이것으로 여러 다양한 상황에서 Ajax요청을 필요에 맞는 방식으로 처리할수 있습니다. (Ajax 직접 접근은 Ext.Ajax 클래스를 살펴보시기 바랍니다) 하지만 여기에서는 기본적인 예제와 실행을 보여드렸습니다.

Ajax 퍼즐의 마지막 조각은 요청과 페이지로 보내는 응답을 담당하는 웹서버측의 처리부분입니다. 이 부분은 서버페이지, 서블릿, HTTP 핸들러, 웹서비스, 펄 혹은 CGI 스크립트 외에 웹 서버 측에서 HTTP 요청을 처리할 수 있는 어떤 기술도 될수 있겠습니다.

결국 이런 다양함으로 인해 표준적인 예제를 제공할 방법이 없습니다. 그래서 주로 사용되는 몇가지 언어로 예제를 만들었는데 독자에게 도움이 되었으면 합니다. (이 코드는 단순히 'name' 필드로 전달되는 입력 값을 다시 클라이언트 측에 'from Server: '에 붙여서 전달하고 'msg' div에 기록됩니다.) PHP 예제는 'ajax-example.php'로 다운로드를 제공하고 있지만 여러분의 서버에 맞는 코드로 수정해서 사용하시기 바랍니다.

ajax-example.php
<?php
if
(isset($_POST['name'])){
    echo 'from Server: '.$_POST['name'];
}
?>

실전에서는 Ajax 처리를 할때는 정확한 처리와 서버에서 오는 데이터 구조를 다루기 위해 땜방코드(--;)를 필요로 합니다. 사람들이 주로 사용하는 몇가지 포맷이 있는데(대부분 JSON or XML) Ext가 서버측 언어에 중립적인 것처럼 Ajax처리를 위해 많은 특정 언어 기반의 라이브러리가 Ext와 잘 연동됩니다.

페이지로 오는 데이터의 구조가 올바르면 서버의 어떠한 동작 방식에도 신경쓰지 않습니다.(^^) 서버측 프레임워크와 툴에 대한 부가적인 정보를 얻고 싶으면 우리의 platfrom-specific resources 목록을 살펴보시기 바랍니다.


- What's Next?


이제 Ext가 무엇이고 어떤 것을 제공하는지 맛을 살짝 보았습니다. 다음 단계로 진입하기 위해 도움이 될 많은 자료가 여러분을 기다라고 있습니다.


#Next Topic: Basic Login
Posted by 1010
반응형
일반적인 JavaScript Learning Guide

참고사이트

  1. Mozilla Developer Center: Core JavaScript 1.5 Reference Manual
  2. Yahoo UI개발자인 Douglas Crockford's JavaScript
  3. Yahoo Developer Network : YUI Theater  ( 더글라스 크록포드의 동영상 강의 수록)
  4. Peter-Paul Koch의 QuirksMode
  5. http://home.cogeco.ca/~ve3ll/jstutor0.htm

그외 볼만한 사이트(Dead Trees)

  1. JavaScript: The Definitive Guide by David Flanagan
  2. Pro JavaScript Techniques by John Resig
  3. Ajax and REST Recipes by Christian Gross
  4. ppk on JavaScript by Peter-Paul Koch
  5. Professional JavaScript for Web Developers by Nicholas C. Zakas
  6. Ajax Patterns and Best Practices by Christian Gross
  7. Dynamic HTML by Danny Goodman
  8. Head First Design Patterns by Freeman & Freeman

OO JavaScript 참조사이트

  1. How to achieve private, public, and privileged members in JavaScript, by Dustin Diaz.
    : Method scoping에 대한 좋은 설명
  2. OOP in JS, Part 1 : Public/Private Variables and Methods, by Gavin Kistner.
    : Scoping 및 prototyping에 대한 샘플
  3. A JavaScript Module Pattern, by Eric Miraglia in YUI Blog.
    : 더글라스 크록포드가 얘기한 module pattern에 대한 설명
  4. Again with the Module Pattern - reveal something to the world, by Christian Heilmann.
    : 모듈패턴
  5. JavaScript for Object-Oriented Programmers (Appendix B of the book AJAX in Action).

DOM




그외 기술


Yahoo! User Interface Library (YUI)

 

Ext JS 은 yui-ext에서 부터 시작되었다. 아래 사이트에서 YUI에 대해서 좀 봐두는것도 좋을지도..

  1. YUI Library
  2. ydn-javascript: Yahoo! User Interface Library Group
  3. YUI Blog

JSON 관련




Platform-Specific Resources


ExtJS를 서버사이드 프레임웍으로 사용한 녀석들.....

PHP

대표적인 샘플코드는 모두 PHP코드로 되어 있는 걸 보면  PHP에서 개발하기 가장 쉬운것 같음.
ExtJS 내장 PHP프레임웍 :  Qcodo Development Framework

Java


Direct Web Remoting (DWR) : http://getahead.org/dwr

.NET


  • AjaxPro 는 .Net 을 이용한 서버사이드 Ajax
  • Jayrock  :  .Net에 JSON / JSON-RPC 를 이용 
  • Json.NET  : .Net에서 JSON을 쓰게 만들어주는 라이브러리 (PHP의 toJSON()이나, Struts의 JSON과 같은건가 보다... ㅡ.,ㅡ; ) 

Ruby on Rails

Ext plugin - ROR는 내장 플러그인으로 작동하므로 gem을 이용해 받으면 되겠다...  (찾기가 더 힘드네.. ㅡ.,ㅡ;)

IBM Lotus Notes/Domino


IBM's Lotus Notes/Domino : IBM 머찌다라는 말만..



통합개발툴(IDE)

Eclipse Based IDEs

Eclipse 은 오픈소스 통합개발툴 (among other things!)이다. ExtJS개발을 위해 이클립스를 사용하기 위해서는 먼저 자바스크립트 사용할수 있는 플러그인을 설치해야 한다.
아래의 플러그인을 추천한다.

  • Aptana - JavaScript, HTML, CSS, PHP languages, FTP/SFTP 지원, RIA/Web2.0등 Ajax 관련 프로젝트에 적합 (느리다는 단점이 있음.. ㅠ.,ㅠ)
  • Spket - JavaScript, XUL, SVG, Laszlo, Silverlight,등 각 모듈 라이브러리 지원(http://blog.naver.com/techbug/150024518549 )
  • JSEclipse - JavaScript

위에 열거된 플러그 인들은 각자 자바스크립트 에디터를 포함하고 있다.  자바스크립트를 열때 "Open with"로 열어서 사용하도록...플러그인을 선택할때는 코드 assist를 지원하는지 확인해 봐야 할듯


Aptana + Spket + ExtJS(강추..)
  • Aptana다운로드 http://www.aptana.com/download_all.php
  • Aptana > Help > Software Updates > Find andInstall > Search for new features to install > New remote site..> "http://www.spket.com/update/"
  • Spket설치 ( Spket IDE Tutorial )
    1. Window > Preferences > Spket > JavaScript Profiles > New > "ExtJS"
    2. "ExtJS" 선택하고  "Add Library"에서 "ExtJS"선택
    3.  "ExtJS" 선택하고 "Add File", 에서 "./ext-2.0/source" 디렉토리에서 "ext.jsb"를 선택
    4. ExtJS profile을 디폴트로 선택
    5. Aptana 플러그인을 새 시작
    6. 새로운 JS파일을 만들면 ExtJS의 Code completion options를 볼수 있다.

AptanaIDE

  • Aptana는 상당히 매력적인 플러그인다. 대부분의 Ajax Library를 제공한다.




다양한 디버깅툴

Firebug (FF에서 강추)


Firebug는 Firefox에 애드온되어 작용하는데 웹페이지의 내용(CSS,HTML,Javscript등)을 실시간으로 볼수있는 상당히 매력적인 도구이다.


Screencasts


Tutorials


다른 브라우저에서 Firebug console을 이용하기

HTTP Trafic Viewer


피들러는 서버와 PC사이의 HTTP 트래픽 로그를 볼수 있는 디버깅 프록시이다. IE전용이나 Firefox의 proxy고급옵션에서 사용할수 있으며 자신이 원하는대로 필터링 하여 사용할수 있다.

MS Script Editor


IE Web Developper

IE WebDeveloper는 인터넷 익스플로러 애드온 프로그램이다.

Testing Data Generator

SQL,CSV,xml, excel등 테스트 데이타를 생성해준다.

http://www.benjaminkeen.com/software/data_generator/

YSlow

YSlow는  rules for high performance web sites를 기반으로 현재 페이지의 속도를 분석해준다. YSlow 는 Firefox 애드온 프로그램으로 인기가 있다.Firebug web development tool.

  • Performance report card
  • HTTP/HTML summary
  • List of components in the page
  • Tools including JSLint

http://developer.yahoo.com/yslow/

DebugBar - IE 플러그인 (강추)


  • DOM Inspector,
  • HTTP Inspector
  • Javascript Inspector and Javascript Console
  • HTML Validator
  • And many more features

http://www.debugbar.com/?langage=en

-->


출처 : http://jaywill.springnote.com/pages/1601738

Posted by 1010
반응형
오늘자 ExtJs 공식 블로그에 Intergrating Google Maps API With ExtJS 라는 글이 포스팅 되었다.

ExtJS 의 Panel 을 확장해서 만든 GMapPanel 을 이용한 샘플이 공개 되었는데 Google Maps API를 이용했다.
재미있는것은 Google 의 StreetView 도 Panel 를 확장해서 구현했단는 것.

사용자 삽입 이미지

지난달 초에 ExtJS 의 Web Desktop 샘플코드를 이용해서 NaverMap API 를 적용한 코드를 작성한 바 있는데 이를 소개할까 한다.

데모보기
사용자 삽입 이미지


Source Code (일부)
MyDesktop.MapWindow = Ext.extend(Ext.app.Module, {
id: 'map-win',
init: function(){
this.launcher = {
text: 'Where we are ?',
iconCls: 'icon-map',
handler: this.createWindow,
scope: this
}
},
createWindow: function(){
var desktop = this.app.getDesktop();
var win = desktop.getWindow('map-win');
var mapObj = null;

function centerMap(){
if (mapObj != null) {
mapObj.setCenterAndZoom(new NPoint(316350, 550250), 2);
}
}

if (!win) {
win = desktop.createWindow({
id: 'map-win',
title: 'Where we are?',
width: 740,
height: 480,
minHeight: 400,
minWidth: 500,
iconCls: 'icon-map',
shim: false,
animCollapse: false,
constrainHeader: true,
layout: 'fit',
tbar: ['서울특별시 성동구 성수1가2동 리버하우스', '->',
{
xtype: 'button',
iconCls: 'map-init',
text: '초기화',
handler: centerMap,
scope: this
}],
listeners: {
beforeshow: function(){
if (mapObj == null) { //최초 생성
mapObj = new NMap(this.body.dom);
mapObj.enableWheelZoom();
centerMap();
var zoom = new NZoomControl();
if (Ext.isIE6) {
var cm = new NMark(
new NPoint(316325, 550245),
new NIcon('images/here.gif',
new NSize(68, 50),
new NSize(34, 48)
)

)
} else {
var cm = new NMark(
new NPoint(316325, 550245),
new NIcon(
'images/here.png',
new NSize(68, 50),
new NSize(34, 48)
)

)
}
NEvent.addListener(cm, 'click', function(){
var w = new Ext.Window({
animateTarget: win.getEl(),
modal: true,
iconCls: 'icon-map',
title: '리버하우스 B동 207호',
html: '<img src="images/riverhouse.jpg">',
width: 360,
autoHeight: true,
resizable: false,
stateful: false
});
w.show();
});

cm.show();
zoom.setAlign("right");
zoom.setValign("top");
mapObj.addControl(zoom);
mapObj.addOverlay(cm);

} else { //생성된 적이 있다면!!
if (this.animateTarget == null) { //Close 상태
this.taskButton = desktop.taskbar.addTaskButton(this);
centerMap();
}
this.animateTarget = this.taskButton.el;
}

},
beforeclose: function(){
this.backupTarget = this.animateTarget;
this.animateTarget = null;
this.fireEvent('close', this); //taskButton remove
this.hide();
return false;
},
bodyresize: function(){
if (this.rendered && mapObj != null) {
mapObj.resize();
}
},
scope: win
}
});
}
win.show();
}
});

Web Desktop 의 작동방식은 바탕화면의 아이콘이나 시작버튼의 메뉴를 클릭하게 되면 Window 를 생성해서 화면에 보여주게 되는데 이때의 Window 는 별도의 객체에 의해서 생성된다. App 라는 Class 인데 Factory 이자 Status 를 관리하는 Manager 역할도 한다.
NaverMap과 연동하기 위한 코드는 코드상의 볼드 처리된 부분이며 주의할 점은

1. NaverMap API 는 한번만 초기화 되어야 한다.
Web Desktop 은 생성된 Window가 Close 될때 Destroy 하게 설계가 되어있다. 하지만 NaverMap 은 별도로 destroy를 할 수 있는 방법을 제공하지 않는다.
  1. NMap 을 전역으로 사용하던가
  2. mapWindow 의 멤버로 이용하려면 close 할때 window 를 destroy 하지 말고 hide 하는 방식을 취해야 한다.
상단의 코드는 후자의 방식을 택하고 있고, 파란색 beforeclose 리스너에서 hide 를 호출하고 Desktop App Manager 에서는 윈도우가 닫힌 것으로 인식하게 끔 close 이벤트를 발생시키고 있다.

2. Window resize 를 고려해야 한다.
우선 NMap 을 생성할 때 사이즈에 관한 인자를 주지 않으면 자동으로 컨테이너 사이즈로 생성됨을 확인하였다.
Window resize 이벤트가 발생할 때 NMap 의 인스턴스의 resize() 를 호출하야 한다. (소스코드 보라색)

그러나
사실 Web Desktop 에서 급히 쓰기해서 NaverMap 과의 연동부분이 샘플코드에 인라인으로 코딩이 되었지만 ExtJS 공식블로그에서 소개한 바와 같이 Panel을 확장해서 새로운 클래스로 만드는 편이 재사용을 위해 100만배는 좋다.
Posted by 1010
반응형
원본 : http://greghoustondesign.com
데모 : http://greghoustondesign.com/demos/mocha/
다운로드 : Download Mocha UI v0.5
소스 : View mocha.js

Mocha 는 MooTools의 유저 인터페이스 클래스이구요 캔버스 태그와 그래픽적 요소를 가지고 만들어 졌습니다.
어머나 너무 씸플해요!!

사용자 삽입 이미지


짬을 내서 UI 적으로 비주얼한 부분을 만들어 봐야 할까봐요...
백날 보이지 않는 소스 개발해봐야.. 알아주는 사람도 없구 ^^

그것 보다 비쥬얼한 부분이 웹에서도 비쥬얼한 부분이 예전에 비해 Web2.0 패러다임이 나오면서 더욱 강조되고 있는것 같습니다. 또한 크로스 브라우징이 가능한...!!

위의 데모에서 보면 알 수 있듯이 정말 심플하고 원래 Drag & Drop 방식의 UI는 CPU점유율이 높아
저 사양 PC에서는 버벅거리는 현상을 발생하는데요.

Mocha UI의 CPU 점유율 테스트 결과 입니다.

사용자 삽입 이미지
이는 기본적인 이동 시에 CPU 점유율(녹색)입니다. 최대 약 47%까지

사용자 삽입 이미지
리사이즈 시에 CPU 점유율(녹색)입니다.  최대 약 50%까지

사용자 삽입 이미지
최대화 시에 CPU 점유율(녹색)입니다.  최대 약 5.38%까지

별 의미 없는 테스트 일 수도 있겠네요. 컴퓨터 사양이 좋아서 말이죠.. ^^
Posted by 1010
반응형
사용자 삽입 이미지
Mootools 에서 Calendar 컴포넌트가 나왔네요.

몇일전에도 심플리티 캘린더라이브러리를 소개했었는데요.

이번 라이브러리는 깜찍하네요. 활용도가 높을꺼 같아요.

CSS-styling hooks 과 적절한 element 사용으로 사용자 정의 UI(?) 가능하게 구현하였네요.




API
  1. myCal1 = new Calendar(  
  2.                     { date1: 'd/m/Y' },   
  3.                     { direction: 1 }  
  4.              );  
  5.  
  6. myCal2 = new Calendar(  
  7.                     { date2: 'd/m/Y' },   
  8.                     { classes: ['dashboard', ... ], direction: 1 }  
  9.             );  
  10.  
  11. myCal3 = new Calendar(  
  12.                     { date3: 'd/m/Y' },   
  13.                     { classes: ['i-heart-ny', ... ], direction: 1 }  
  14.             );  
Posted by 1010