2009年4月21日星期二

jQuery教學(1) - GridView/Table中使用Selectors

這段時間在公司比較空閒,做了幾個Sample,順道放上來介紹一下jQuery。
我會講下jQuery中的Core Function / Event /Selectors / Effect的用法,和Ajax如何Call ASP.NET Web Service/Page Method,以及如何對JSON做Serialization 和 Deserialization。

其實大家都知道ASP.NET的GridView Control在Browser顯示是以Table形式顯示,唯一特別的地方是GridView的Header的Cell是用<th>表示,而Row的Cell則用<td>,所以GridView和一般HTML是可以混為一談的。

有時候我們會想知道Table中某一行某一格的Value是什麼,又或者想因應不同情況要Apply CSS去其中一格,當然在Server-Side那邊,在Row Collection中找尋是很容易。但在Client-Side用上JavaScript,要在DOM中找尋Table再找尋特定的Cell都會很麻煩。

先看看Demo :


jQuery的Selectors最強的地方就是可以在整個HTML文件中穿梭,即使遇上很複雜的Table,只要是正確的DOM文件,你亦可以很容易找到你想要的,而jQuery的Selectors有很多種運作模式,務求用最少的Code去做最多的工作。

此文就以這個Table做範例,有三個Column,五個Row去示範如何用Selector去取得Cell的Column index和Row Index,同時亦相反地用Index去取得Cell中的Value。當然就如之前所講,此Table等同Browser中的GridView Control。

Table的HTML :
<!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 runat="server">
    <title></title>
</head>
<body style="font-family: Tahoma; font-size: 11px;">
    <table id="gridtable">
        <!--&#32202;&#35352;&#21152;&#19978;id-->
        <tr>
            <th>Product id</th>
            <th>Console Name</th>
            <th>Colour</th>
        </tr>
        <tr>
            <td>1</td>
            <td>Play Station 3</td>
            <td>Black</td>
        </tr>
        <tr>
            <td>4</td>
            <td>Xbox 360</td>
            <td>White</td>
        </tr>
        <tr>
            <td>11</td>
            <td>NDSL</td>
            <td>Red</td>
        </tr>
        <tr>
            <td>18</td>
            <td>PSP</td>
            <td>Silver</td>
        </tr>
        <tr>
            <td>26</td>
            <td>Wii</td>
            <td>White</td>
        </tr>
    </table>
</body>
</html>

首先第一步當然就是jQuery的js檔。其實大家可以直接引用Google-Host的jQuery或者jQuery官網上的。
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

再來就是Javascript部份,我要做的是,當Click每一個Cell時,會alert出三個Index值,分別是TD在Table中順序的Index / TD在那個TR的Column Index和Row在Table中的Row Index。
<script type="text/javascript">
        $(document).ready(function () {
            $('#btnGetCell').click(function () {
                var col = $('#colindex').val();
                var row = parseInt($('#rowindex').val()) + 1;
                var result = $('#gridtable tr:eq(' + row + ') td:eq(' + col + ')').html();
                alert('value is : ' + result);
            })

            $('#gridtable tr td').click(function () {
                alert('cell index in table : ' + $('td').index(this));
                alert('cell index in selected row : ' + this.cellIndex);
                alert('row index in grid : ' + (this.parentNode.rowIndex - 1));
            })
        });
    </script>

第二行的$(document).ready是很重要的,因為這代表了Page_Load的Event,把底下的function載入。
只需要定義一次就可以,可以如上面一樣,同時把多個不同的function放進ready event之中。

第一個btnGetCell click的Function就是使用Selector取得Index,而Selector都是由'$'開始,例如$('#btnGetCell') , '#'之後的就是element的ID,之後的#colindex和#rowindex加val()就是要取得TextBox中的value。而val(),html(),text()三者是不同的, val()是取得如input當中的value,而html()則是innerHTML,例如<td>123</td>中的'123,而text()則同html()相似,但會省略其他的Tag,例如<p><b>Hello</b> World</p>,當我使用alert($("p").text()); 便會出現Hello World,而不是<b>Hello</b> World

值得一提的就是'eq',
一般情況下Selector可以是階層式運作,例如我要Table中的TR中的TD,我可以寫成$('#gridtable tr td'),但一個TR中會有多個TD,這時就要寫成$('#gridtable tr td:eq(2)')。
2代表Index,是Zero-Base,亦即是第三個TD。

至於第二個Function,中的this代表TD的Collection,大家可以奇怪為什麼會Skip了Header的Cell。其實這就是Selector其中一種的工作方式,因為如之前所說Header是TR->TH ,而不是TR -> TD。所以在第二個function中,一切Header的th cell都會省卻。

而this.cellIndex和this.parentNode.rowIndex 則是HTML DOM properties,與jQuery無關,但亦同時顯示到jQuery利害之處就是能配合傳統的Javascript和HTML工作。

下次,我會講下使用jQuery的animate effect和slide effect。

完整的網頁HTML碼:
<!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>
    <title>亞特蘭提斯 Net Atlantis - jQuery教學(1) - GridView/Table中使用Selectors</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            $('#btnGetCell').click(function () { //Event Helpers
                var col = $('#colindex').val();
                var row = parseInt($('#rowindex').val()) + 1;
                var result = $('#gridtable tr:eq(' + row + ') td:eq(' + col + ')').html();
                alert('value is : ' + result);
            })

            //http://www.quirksmode.org/dom/w3c_html.html 
            //http://www.quirksmode.org/dom/tests/tablesIndices.html
            $('#gridtable tr td').click(function () {
                alert('cell index in dom : ' + $('td').index(this));
                alert('cell index in selected row : ' + this.cellIndex);
                alert('row index in grid : ' + (this.parentNode.rowIndex - 1));
            })

        }); //<--End ready event
    </script>
    <style type="text/css">
        body
        {
            font: small arial;
        }
        tr:first-child
        {
            background-color: #F5F5DC;
        }
        tr:first-child:hover
        {
            background-color: #F5F5DC;
        }
        tr:hover
        {
            background-color: #E8FFEC;
            cursor: pointer;
        }
        td
        {
            border: #ccc 1px solid;
            text-align: center;
            width: 100px;
        }
        td:hover
        {
            background-color: #E8FFEC;
            border: #666 1px solid;
            width: 100px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <table id="gridtable">
    <tr>
    <th>Product id</th><th>Console Name</th><th>Colour</th>
    </tr>
    <tr>
    <td>1</td><td>Play Station 3</td><td>Black</td>
    </tr>
    <tr>
    <td>4 </td><td>Xbox 360</td><td>White</td>
    </tr>
    <tr>
    <td>11 </td><td>NDSL</td><td>Red</td>
    </tr>
    <tr>
    <td>18</td><td>PSP</td><td>Silver</td>
    </tr>
    <tr>
    <td>26</td><td>Wii</td><td>White</td>
    </tr>
    </table>
    column index :<input id="colindex" type="text" size="1" value="1" />
    row index :<input id="rowindex" type="text" size="1" value="1" />
    <button id="btnGetCell">Get Cell Value</button>
</body>
</html>

3 則留言:

  1. That was one of the funniest things I think I've ever read.
    I'd be honored if you would consider linking your blog to mine
    Keep up the good work-- and to the Cons who are complaining, you really need to work a little harder at reading comprehension.

    回覆刪除
  2. I think that this post is very good because has useful information.

    回覆刪除