출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using the tablesorter plugin
http://tablesorter.com/docs/
$("#myTable").tablesorter();
---------------------------------------------
<table id="myTable">
<thead>
<tr>
    <th>Last Name</th>
    <th>First Name</th>
    <th>Email</th>
    <th>Due</th>
    <th>Web Site</th>
</tr>
</thead>
<tbody>
<tr>
    <td>Smith</td>
    <td>John</td>
    <td>jsmith@gmail.com</td>
    <td>$50.00</td>
    <td>http://www.jsmith.com</td>
</tr>
<tr>
    <td>Bach</td>
    <td>Frank</td>
    <td>fbach@yahoo.com</td>
    <td>$50.00</td>
    <td>http://www.frank.com</td>
</tr>
<tr>
    <td>Doe</td>
    <td>Jason</td>
    <td>jdoe@hotmail.com</td>
    <td>$100.00</td>
    <td>http://www.jdoe.com</td>
</tr>
<tr>
    <td>Conway</td>
    <td>Tim</td>
    <td>tconway@earthlink.net</td>
    <td>$50.00</td>
    <td>http://www.timconway.com</td>
</tr>
</tbody>
</table>
<thread> 태그 안에 있는 것을 클릭하면 테이블을 정렬한다. 신기하네...
숫자, 문자 등을 알아서 판별한다고 하는군. 상세한 것은 위의 링크를 참조.

$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
This tells tablesorter to sort on the first and second column in ascending order.
정렬 초기값 설정.

Sort multiple columns simultaneously by holding down the shift key and clicking a second, third or even fourth column header!
하나 선택해서 그걸 기준으로 정렬하고 쉬프트 클릭하고 다른 것 선택하면 계단식으로 정렬됨(기존 정렬을 기준으로 다시 정렬).

속도만 받쳐주면 테이블 정렬은 이걸로 해도 될듯?!
출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using Effects
$(document).ready(function(){
   $("a").toggle(function(){
     $(".stuff").hide('slow');
   },function(){
     $(".stuff").show('fast');
   });
 });
소스 버전이 옛날 것인가... 제대로 동작하질 않는군..

http://docs.jquery.com/Effects/toggle
위의 링크된 문서를 참고할 것

$(document).ready(function() {
    $("#btn1").click(function() {
        $("p").toggle();
        $("#hbtn").toggle();
    });
});

-----------------------------------------

<button id="btn1">Toggle</button>
<p class="tg">Hello</p>
<p class="tg" style="display: none;">Toggle!</p>
<p>AAA</p>
<p style="display: none;">BBB</p>
<button id="hbtn" style="display: none;">hidden button</button>
해보면 toggle()한 display:none이 아닌 것은 안보이게 되고, display:none이었던 것은 보이게된다.

var flip = 0;
$("button").click(function () {
    $("p").toggle( flip++ % 2 == 0 );
});
toggle(XXX)안에 식을 넣는 것도 가능. true면 보이고, false면 숨긴다.

$("button").click(function () {
    $("p").toggle("slow");
});
toggle("slow"). 천천히 사라지고 천천히 나타남.
slow, fast, normal 이 있고, 직접 밀리세컨드로 속도를 지정할 수 있다.

$("button").click(function () {
    $("p").toggle("slow", doCallback);
});

function doCallback() {
    // do something
    this; // DOM element
}
이런 식으로 토글 이펙트가 끝났을 때 실행될 callback 함수도 지정 가능.
여러 개가 토글 되는 경우 각각 실행됨.
사라지는 토글이라고 해서 사라지는 DOM의 callback만 실행되는 것이 아니라, 나타나는 DOM의 callback도 실행된다.
즉 어찌됐든 토글되는 모든 DOM의 callback이 실행됨.

기타 Effects는 아래 링크를 참조.
http://docs.jquery.com/Effects

Animate
// 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 );
});
---------------------------------------------------
<button id="go">» Run</button>
<div id="block">Hello!</div>
#block이 초기 모양에서 animate({XXX}, YYY)에 설정된 모양(XXX)으로 변형된다. 이 때, YYY는 변형 시간(클 수록 천천히).

$("#go1").click(function(){
    $("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } )
         .animate( { fontSize:"24px" }, 1500 )
         .animate( { borderRightWidth:"15px" }, 1500
    );
});

$("#go2").click(function(){
    $("#block2").animate( { width:"90%"}, 1000 )
         .animate( { fontSize:"24px" } , 1000 )
         .animate( { borderLeftWidth:"15px" }, 1000
    );
});

$("#go3").click(function(){
    $("#go1").add("#go2").click();
});

$("#go4").click(function(){
    $("div").css({width:"", fontSize:"", borderWidth:""});
});
---------------------------------------------------
<button id="go1">» Animate Block1</button>
<button id="go2">» Animate Block2</button>
<button id="go3">» Animate Both</button>
<button id="go4">» Reset</button>
<div id="block1">Block1</div>
<div id="block2">Block2</div>
$("#ID").animate({AAA},AAA).animate({BBB},BBB).animate({CCC},CCC); AAA, BBB, CCC의 순서대로 애니메이트됨.
queue:false 옵션이 있으면 순서 상관없이 동시에 애니메이트됨.

$("#go1").add("#go2").click(); go1과 go2를 동시에 클릭 이벤트 발생시킴.


animate()
Arguments:
paramsOptions
A set of style attributes that you wish to animate, and to what end.
duration (Optional)String, Number
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).
easing (Optional)String
The name of the easing effect that you want to use (plugin required). There are two built-in values, "linear" and "swing".
callback (Optional)Function
A function to be executed whenever the animation completes, executes once for each element animated against.

$("p").animate({
      "height": "toggle", "opacity": "toggle"
}, { duration: "slow" });
Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
라는데, height랑 opacity를 토글하는게 무슨 효과인지 모르겠다.

나머진 위의 링크 참조...


'프로그래밍 > Web' 카테고리의 다른 글

[jQuery] jQuery 예제 01  (0) 2009.07.17
[jQuery] Getting Started with jQuery 04  (0) 2009.07.11
[jQuery] Getting Started with jQuery 02  (0) 2009.07.10
[jQuery] Getting Started with jQuery 01  (0) 2009.07.10
[jQuery] How jQuery Works  (0) 2009.07.06
출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using Ajax
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>jQuery Starterkit</title>

<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    // generate markup
    var ratingMarkup = ["Please rate: "];
    for(var i=1; i <= 5; i++) {
        ratingMarkup[ratingMarkup.length] = "<a href='#'>" + i + "</a> ";
    }
    var container = $("#rating");
    // add markup to container
    container.html(ratingMarkup.join(''));
   
    // add click handlers
    container.find("a").click(function(e) {
        e.preventDefault();
        // send requests
        $.post("starterkit/rate.php", {rating: $(this).html()}, function(xml) {
            // format result
            var result = [
                "Thanks for rating, current average: ",
                $("average", xml).text(),
                ", number of votes: ",
                $("count", xml).text()
            ];
            // output result
            $("#rating").html(result.join(''));
        } );
    });
});
</script>

</head>
<body>
<h1>jQuery Getting Started Example - rate me</h1>
<p>This example demonstrate basic use of AJAX. Click one of the links below to rate. The
number of rating and the average rating will be returned from the serverside script and displayed.</p>

<div id="rating">Container</div>

</body>
</html>
$("average", xml).text() -> 결과로 받은 xml에서 <average>XXX</average>를 찾아서 text 값을 가져온다.
딱히 구조(부모-자식)는 상관없는 듯.

기타 참고 사항.
ajax 사용 시 주의점

A very common problem encountered when loading content by Ajax is this: When adding event handlers to your document that should also apply to the loaded content, you have to apply these handlers after the content is loaded. To prevent code duplication, you can delegate to a function.
Example:
function addClickHandlers() {
   $("a.remote", this).click(function() {
     $("#target").load(this.href, addClickHandlers);
   });
 }
 $(document).ready(addClickHandlers);

Now addClickHandlers is called once when the DOM is ready and then everytime when a user clicked a link with the class remote and the content has finished loading.

Note the $("a.remote", this) query, this is passed as a context: For the document ready event, this refers to the document, and it therefore searches the entire document for anchors with class remote. When addClickHandlers is used as a callback for load(), this refers to a different element: In the example, the element with id target. This prevents that the click event is applied again and again to the same links, causing a crash eventually.

Another common problem with callbacks are parameters. You have specified your callback but need to pass an extra parameter. The easiest way to achieve this is to wrap the callback inside another function:
// get some data
 var foobar = ...;
 
 // specify handler, it needs data as a paramter
 function handler(data) {
   //...
 }
 
 // add click handler and pass foobar!
 $('a').click(function(){
   handler(foobar);
 });
 
 // if you need the context of the original handler, use apply:
 $('a').click(function(){
   handler.apply(this, [foobar]);
 });


출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

간단한 부분은 제외.

Using selectors and events

$(document).ready(function() {
   $("#orderedlist").addClass("red");
 });
id가 orderedlist 인 것을 찾아서 red 클래스를 추가

$(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
 });
orderedlist 가 갖는 모든 li 태그에 blue 클래스 추가

$(document).ready(function() {
   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green");
   });
 });
orderedlist 가 갖는 마지막 li 태그 위에 커서가 오면 green 클래스를 추가하고, 커서가 나가면 green 클래스를 제거

$(document).ready(function() {
   $("#orderedlist").find("li").each(function(i) {
     $(this).append( " BAM! " + i );
   });
 });
orderedlist 의 li 태그들을 찾아서, 각각의 li 태그 내의 값(<li>XXX</li>)에 BAM! 현재 카운트를 붙인다.
each(function(i) {...}) 에서 i 가 루프의 현재 카운트 값. 시작은 0.

$(document).ready(function() {
   // use this to reset a single form
   $("#reset").click(function() {
     $("form")[0].reset();
   });
 });

$(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });
폼 리셋하기.
위는 폼이 1개일 때. 밑은 여러 개일 때.

$(document).ready(function() {
   $("li").not(":has(ul)").css("border", "1px solid black");
 });
ul 태그를 갖지 않는 모든 li 태그에 주어진 css 스타일을 적용(border를 1px solid black으로).
원래는 모든 li 태그를 찾고 그 중에서, ul 태그를 갖는 li 태그를 제거.

$(document).ready(function() {
   $("a[name]").css("background", "#eee" );
 });
XPath 형식의 객체 선택.
name 속성을 갖는 a 태그를 선택해서 css 스타일 적용.
출처: http://www.ibm.com/developerworks/kr/library/wa-jquery1/#main
IBM에 올라오는 내용을 따라하면서 첨삭한 것임...

1. 적절하게 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(function() {
    // 여기서 하라는 얘기
});

2. jQuery 체인 연결
 
$("div").addClass("a").show().text("manipulated");

3. jQuery 충돌 해결
jQuery나 다른 자바스크립트 라이브러리를 사용할 때, 서로 어울려 동작하지 않을 경우가 있다는 사실이다. 다시 말해, 라이브러리 두 개 이상을 사용할 경우, 라이브러리 둘 이상에서 변수 "$"를 사용한다면 엔진은 어떤 라이브러리가 "$" 호출을 참조해야 할지 모르는 사태가 벌어진다.이런 문제를 해결하기 위해 jQuery는 "$" 변수를 다른 변수로 사상하는 방법을 제공한다.
j$ = jQuery.noConflict();
j$("div").addClass("a");

4. 선택
모든 jQuery 루트는 페이지에서 특정 엘리먼트를 선택해 다룰 수 있는 능력이 있다. 루트에서, jQuery 선택 과정은 정말 거대한 필터 과정이다. 페이지에 존재하는 모든 엘리먼트를 명령에서 제공하는 필터에 밀어넣은 다음에, 일치하는 객체 자체나 탐색이 가능한 객체 배열을 반환한다. 첫 세 가지 예제가 가장 널리 쓰인다. HTML 태그, ID, CLASS로 객체를 찾아내는 방법이다.

(1) HTML
// 이 예제는 페이지에서 모든 <div> 태그를 보여준다. 여기서
// 처음이나 마지막에 걸리는 태그가 아니라 모든 <div> 태그를 보여줌에 주목하자.
// 배열 탐색은 이 기사 후반부에 다룬다.
$("div").show();

// 페이지에 존재하는 모든 <p> 태그에 붉은 배경색을 부여한다.
$("p").css("background", "#ff0000");

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

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

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

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

(5) 다른 필터
페이지에서 원하는 엘리먼트를 빨리 찾도록 도와주는 다른 필터도 존재한다. 이런 필터는 모두 jQuery 검색 단어에서 필터를 나타내는 ":" 글자로 시작한다. 검색 범주에서 단독으로 사용이 가능하지만, 주로 원하는 구체적인 엘리먼트를 찾기 위해 검색 기준을 튜닝하는 방식으로 앞서 소개한 세 가지 검색 기준과 함께 사용하도록 설계되었다.
// 페이지에서 모든 <p> 태그를 가린다.
$("p").hide();

// 페이지에서 HTML 태그에 무관하게 첫 엘리먼트를 가린다.
$(":first").hide();

// 검색 기준을 좀 더 정교하게 튜닝하게 다듬는 기능을 제공하기 위해 섞어서 사용하는
// 방법을 보여준다. 특정 페이지에서 첫 번째 <p> 태그만 감춘다.
$("p:first").hide();
API 페이지 참조: http://docs.jquery.com/Selectors

(6) 폼 엘리먼트 필터
추가 필터와 마찬가지로 폼 필터도 필터임을 알려주는 ":" 문자로 시작한다. 또한 검색 결과를 좀 더 정교하게 얻기 위해 다른 검색 필터와 섞어서 사용하기도 한다. 따라서 ":text"라는 검색 필터는 페이지에 존재하는 모든 텍스트 필터를 반환하며, ".largeFont:text"라는 검색 필터는 페이지에서 "largeFont" 클래스인 텍스트 필드만 반환한다. 이는 폼 엘리먼트를 정교하게 조작하기 위한 기능을 제공한다.
폼 필터는 또한 개발자가 알아 두면 좋은 내용인 엘리먼트의 개별 속성을 포함한다. 따라서 ":checked", ":disabled", ':selected"와 같은 필터는 검색 기준을 정교하게 지정하도록 사용할 수 있다.
-API 페이지 참고할 것
// class가 deleteCheck인 체크박스 중에서 체크된 것들만 선택
$(".deleteCheck:checked").each(function() {
    // Do Something
});

5. 탐색

each() 함수. 이 함수는 엘리먼트 각각을 순회하며 루프를 돌 때마다 엘리먼트를 하나씩 처리하기에 프로그래밍 측면에서 "for loop"와 동일하다. 추가적으로 "this"(일반적인 자바스크립트 구문을 사용할 경우)나 $(this)(jQuery 명령어를 사용할 경우)로 루프 내에서 각 엘리먼트를 참조할 수 있다.
// 페이지에 있는 각 <p> 태그를 대상으로 순회한다. 여기서 인라인 함수 사용에 주목하자.
// 자바에서 anonymous 클래스와 비슷한 기능이다.
// 개별 함수를 호출하거나 이와 같이 인라인 함수를 작성할 수 있다.

var increment = 1;
$("p").each(function(){

// 이제 태그를 만날 때마다 문단 카운터를 하나씩 더한다. $(this) 변수를 사용해
// 개별 문단 엘리먼트를 참조하는 방법에 주목하자.

$(this).text(increment + ". " + $(this).text());
increment++;
});

(1) 추가적인 배열 함수
// eq() 함수는 직접 배열에 속한 구성 요소를 참조할 때 사용한다.
// 이 경우 세 번째 문단(당연히 0이 시작 기준이다)을 얻은 다음에 감춘다.
$("p").eq(2).hide();

// slice() 함수는 배열에서 처음과 끝 색인을 받아서 새끼 배열을 친다.
// 다음은 페이지에서 세 번째부터 다섯 번째까지 문단을 감춘다.
$("p").slice(2,5).hide();

(2)
next() 함수
<input type=text class=validate><span></span>

function validateForm()
{
$(".validate:text").each(function(){
if ($(this).val()=="")
// 페이지에서 "validate" 클래스로 정의된 각 textfiled를 순회한다.
// 비어 있다면, <span> 바로 뒤에 오류 메시지를 집어 넣는다.

$(this).next().html("This field cannot be blank");
});
}

6.
이 기사에서 배운 내용을 하나로 합치기
웹 메일 테이블에 있는 좌상단 컬럼에 보이는 "Select All"/"Deselect All" 체크 박스에 초점을 맞춘다(아래에 강조했다). 이 체크 박스를 선택하면, 컬럼에 있는 모든 체크 박스를 선택하며, 체크 박스 선택을 해제하면, 컬럼에 있는 모든 체크 박스 선택을 해제한다.
<!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>JQuery Test 01</title>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
   
});

function checkAll() {
    //alert($("#allCheck").attr("checked"));
    if($("#allCheck").attr("checked") == true) {
        // 체크 안 된 개별 선택을 찾아서 갯수 카운트
        var cnt = 0;
        $(".priCheck").each(function() {
            //alert($(this).val() + " : " + $(this).attr("checked"));
            if($(this).attr("checked") != true) {
                cnt++;
            }
        });

        //alert("false : " + cnt);

        // 모두 checked로
        $(".priCheck").each(function() {
            $(this).attr("checked", true);
        });
    }
    else {
        // 체크된 개별 선택을 찾아서 갯수 카운트
        var cnt = 0;
        $(".priCheck:checked").each(function() {
            //alert($(this).val() + " : " + $(this).attr("checked"));
            cnt++;
        });

        //alert("false : " + cnt);

        // 모두 unchecked로
        $(".priCheck").each(function() {
            $(this).attr("checked", false);
        });
    }
}
</script>
</head>
<body>
<table>
    <tr>
        <td><input type="checkbox" id="allCheck" onclick="checkAll();" value="AAA"></td>
        <td>전체 선택</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="priCheck" value="1"></td>
        <td>개별 선택1</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="priCheck" value="2"></td>
        <td>개별 선택2</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="priCheck" value="3"></td>
        <td>개별 선택3</td>
    </tr>
</table>
</body>
</html>

- :unchecked와 같은 필터는 없음.
- 체크상태로 만들려면 checkbox플러그인을 쓰던가, 아님 $("XXX").attr("checked", true) 사용. attr("속성명", "값")으로 아무 속성이나 설정가능

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