選擇
jQuery 的根本在于它在頁面上選擇和操作某些元素的能力。從某種意義上說,需要圍繞這些對象才能構(gòu)建出有效的 jQuery 庫。因此,面對一個普通 HTML 頁面上提供的大量選項,您需要一種方法來快速高效地選擇您需要在頁面上使用的元素,只選擇需要的元素(不多也不少)。jQuery 如我們所愿地提供了一些強大的選擇方法,幫助我們在頁面上尋找和選擇對象。jQuery 創(chuàng)建了它自己的選擇語法,并且這種語法很容易掌握。
(以下大部分示例所使用的函數(shù)將留在下一篇中討論,不過它們的功能應(yīng)該是很直觀明了的)。
根本上來講,jQuery 中的選擇過程就是一個巨大的過濾過程,頁面上的每個元素都經(jīng)過這個過濾器,它將返回一個匹配的對象,或一個可以遍歷的匹配對象的數(shù)組。
排在前面的 3 個示例是最常用的。它們通過 HTML 標記、ID 或 CLASS 查找對象。
HTML
要獲取一個頁面中所有匹配的 HTML 元素的數(shù)組,您僅需將 HTML 標記(不帶括號)傳遞到 jQuery 搜索字段。這是查找對象的 “快速但是粗糙” 的方法。如果要將屬性附加到通用的 HTML 元素,這種方法是很有用的。
清單 5. HTML 選擇
// This will show every <div> tag in the page. Note that it will show
// every <div>, not the first matching, or the last matching.
// Traversing Arrays is discussed later in the article.
$("div").show();
// This will give a red background to every <p> tag in the page.
$("p").css("background", "#ff0000"); |
ID
正確的頁面設(shè)置要求頁面上的每個 ID 都是惟一的,雖然有時并不是這樣(有意或無意)。使用 ID 選擇時,jQuery 僅返回第一個匹配的元素,因為它要求您遵循正確的頁面設(shè)計。如果您需要將一個標記附加到同一頁面上的幾個元素,應(yīng)當選擇使用 CLASS 標記。
清單 6. ID 選擇
// This will set the innerHTML of a span element with the id of "sampleText" to "Hi".
// Note the initial "#" in the command. This is the syntax used by jQuery to search
// for IDs, and must be included. If it is excluded, jQuery will search for the HTML
// tag instead, and with no <sampleText> tags on a page, will ultimately do
// nothing, leading to frustrating and hard-to-find bugs (not that that has ever
// happened to me of course).
$("#sampleText").html("Hi"); |
CLASS
CLASS 與 ID 非常相似,不同之處是它可以用于一個頁面上的一個或多個元素。因此,盡管受到同一頁面的每個元素只有一個 ID 的限制,同一頁面上的多個元素仍然可以擁有相同的 CLASS。這使您可以在一個頁面上跨多個元素執(zhí)行函數(shù),并且只需傳入一個 CLASS 名稱。
清單 7. CLASS 選擇
// This will create a red background on every element on the page with a CLASS of
// "redBack". Notice that it doesn't matter which HTML element this "redBack"
// CLASS tag is attached to. Also notice the period in the front of the query
// term -- this is the jQuery syntax for finding the CLASS names.
$(".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> |
合并搜索條件
可以在一個搜索中,將以上的 3 個搜索條件和下面的所有過濾器合并起來。通過使用 “,” 分隔每個搜索條件,搜索將返回與搜索詞匹配的一組結(jié)果。
清單 8. 合并搜索
// This will hide every <p>, <span>, or <div>.
$("p, span, div").hide(); |
更多的過濾器
雖然在 jQuery 中,這 3 個搜索參數(shù)無疑是最常用的,但還有許多其他搜索參數(shù),可以幫助您在一個頁面上快速查找所需的元素。這些過濾器以 “:” 開頭,表明它們是 jQuery 搜索詞中的過濾器。盡管它們也可以作為獨立的搜索條件,但是設(shè)計它們的目的是將它們和以上 3 個搜索條件一起使用,從而可以調(diào)整搜索條件以找到您需要的特定元素。
清單 9. 更多的過濾器
// This will hide every <p> tag on a page
$("p").hide();
// This will hide the first element on a page, no matter its HTML tag
$(":first").hide();
// Notice how these can be used in combination to provide more fine tuning of
// search criteria. This will hide only the first <p> tag on a given page.
$("p:first").hide(); |
可以將多個過濾器用作搜索元素。雖然在這里我沒有列舉所有的過濾器(這是 API 頁面的任務(wù)),但其中一些過濾器在處理頁面和搜索元素方面非常方便。
我將 主要關(guān)注 Selection 包中一些非常重要的過濾器,它們就是表單 元素過濾器。如今的富 Internet 應(yīng)用程序比較關(guān)注表單及包含在其內(nèi)的元素(文本字段、按鈕、復(fù)選框、單選按鈕等),它們從服務(wù)器收集和傳輸信息,或收集信息并傳輸?shù)椒?wù)器。由于它們在 RIA 中的重要作用,在當今的 Web 應(yīng)用程序中,這些過濾器在處理 jQuery 時非常重要。
這些過濾器和前面介紹的過濾器的工作原理是一樣的,并且也是以 “:” 開頭,表明它們是過濾器。同樣,它們也可以和其他搜索過濾器一起使用,以細化搜索條件。因此,一個 “:text” 搜索過濾器將返回頁面上的每個文本字段,而一個 “.largeFont:text” 搜索過濾器僅返回頁面上作為 “l(fā)argeFont” 類的一部分的文本字段。這允許進一步細化和操作表單元素。
表單過濾器也包括元素的每個屬性,了解這方面的知識對開發(fā)人員有好處。因此像 “:checked”、“:disabled” 和 “:selected” 等搜索過濾器將為特定的搜索進一步細化搜索條件。
遍歷
現(xiàn)在,您已經(jīng)學(xué)會如何搜索和過濾頁面上的所有元素,接下來需要一種高效的方法來遍歷結(jié)果,進一步處理元素。自然,jQuery 提供了幾種遍歷搜索結(jié)果的方法。
第一個也是最常用的遍歷方法是 each() 函數(shù)。這和 “for loop” 的功能是一樣的,遍歷每個元素并通過迭代遞增元素。此外,循環(huán)中的每個元素的引用可以通過 “this”(用于一般的 JavaScript 語法)或 $(this)(用于 jQuery 命令)來實現(xiàn)。
讓我們看看下面的示例。
清單 10. each 循環(huán)
// Will loop through each <p> tag on the page. Notice the use of the
// inline function here -- this is analogous with the anonymous classes in Java.
// You can either call a separate function, or write an inline function like this.
var increment = 1;
$("p").each(function(){
// now add a paragraph count in front of each of them. Notice how we use the
// $(this) variable to reference each of the paragraph elements individually.
$(this).text(increment + ". " + $(this).text());
increment++;
}); |
因為搜索結(jié)果存儲在一個數(shù)組中,您肯定希望函數(shù)遍歷該數(shù)組,就像處理其他編程語言的數(shù)據(jù)對象一樣。因此,要查找一個給定搜索結(jié)果的長度,則可以在該數(shù)組上調(diào)用 $().length。清單 11 展示了更多的數(shù)組遍歷函數(shù),可適用于其他編程語言的數(shù)組遍歷。
清單 11. 其他數(shù)組函數(shù)
// the eq() function lets you reference an element in the array directly.
// In this case, it will get the 3rd paragraph (0 referenced of course) and hide it
$("p").eq(2).hide();
// The slice() function lets you input a start and an end index in the array, to
// create a subset of the array. This will hide the 3rd through 5th paragraphs on the
// page
$("p").slice(2,5).hide(); |
除了這些數(shù)組遍歷函數(shù)之外,jQuery 還提供了一些函數(shù),使您可以查找嵌套在搜索詞周圍的元素。為什么這很有用呢?例如,我們常常需要在圖片的旁邊嵌入一個文本標簽,或在表單元素旁邊嵌入一個錯誤消息。使用這些命令可以查找特定的表單元素,然后通過將表單元素放置在下一個元素(span 標記)中,把該錯誤消息直接放置在表單元素旁邊。清單 12 顯示了這種設(shè)計的一個示例:
清單 12. 示例 next() 函數(shù)
<input type=text class=validate><span></span>
function validateForm()
{
$(".validate:text").each(function(){
if ($(this).val()=="")
// We'll loop through each textfield on the page with a class of "validate"
// and if they are blank, we will put text in the <span> immediately afterwards
// with the error message.
$(this).next().html("This field cannot be blank");
});
} |
綜合學(xué)到的知識
要了解如何結(jié)合使用以上知識,可以查看本文包含的示例應(yīng)用程序(參見 參考資料 小節(jié))。
現(xiàn)在簡單介紹一下示例應(yīng)用程序。我將在本系列所有文章中使用這個示例應(yīng)用程序,因為它使用了大量不同的 jQuery 示例,并且?guī)缀跛腥硕际煜み@個應(yīng)用程序 — 一個處理 Web 郵件的富 Internet 應(yīng)用程序。這個示例應(yīng)用程序是一個簡單的郵件客戶機,它利用 jQuery 給用戶這樣的感覺:該電子郵件客戶機非常類似于桌面應(yīng)用程序。在最后一篇文章結(jié)束時,您將明白這個簡單的應(yīng)用程序是如何為用戶制造這種感覺的,并且明白使用 jQuery 實現(xiàn)這個功能是多么簡單。
本文的重點是 “Select All”/“Deselect All” 復(fù)選框,它們出現(xiàn)在 Web 郵件表(下面突出顯示)的左側(cè)列的頂部。當選中該復(fù)選框時,它將選擇該列的每個復(fù)選框;取消選擇該復(fù)選框時,它將取消選擇該列的所有復(fù)選框。
圖 2. “Select All” 復(fù)選框

清單 13. 綜合學(xué)到的知識
<!-- The first step is creating the Select All checkbox itself.
we give it a unique ID on the page -->
<input type=checkbox id=selectall>
<!-- The next step is giving each of the rows their own checkbox.
we put each row's checkbox into the 'selectable' class, since there can be many rows,
and we want each of the rows' checkboxes to have the same behavior. -->
<input type=checkbox class=selectable>
<!-- The final step is bringing it all together with some jQuery code. -->
// remember that all jQuery setup code must be in this document.ready() function,
// or contained within its own function in order to function correctly.
$(document).ready(function(){
// We use the jQuery selection syntax to find the selectall checkbox on the page
// (note the '#' which signifies ID), and we tell jQuery to call the selectAll()
// function every time someone clicks on the checkbox (we'll get to Events in a
// future article).
$("#selectall").click(selectAll);
});
// This function will get called every time someone clicks on the selectall checkbox
function selectAll()
{
// this line determines if the selectall checkbox is checked or not. The attr()
// function, discussed in a future article, simply returns an attribute on the
// given object. In this case, it returns a boolean if true, or an undefined if
// it's not checked.
var checked = $("#selectall").attr("checked");
// Now we use the jQuery selection syntax to find all the checkboxes on the page
// with the selectable class added to them (each row's checkbox). We get an array
// of results back from this selection, and we can iterate through them using the
// each() function, letting us work with each result one at a time. Inside the
// each() function, we can use the $(this) variable to reference each individual
// result. Thus, inside each loop, it finds the value of each checkbox and matches
// it to the selectall checkbox.
$(".selectable").each(function(){
var subChecked = $(this).attr("checked");
if (subChecked != checked)
$(this).click();
});
} |
結(jié)束語
jQuery 是 Web 應(yīng)用程序開發(fā)社區(qū)中非常受歡迎的 JavaScript 庫,并且隨著富 Internet 應(yīng)用程序越來越普及,它將變得更加重要。由于許多公司都在線遷移內(nèi)部應(yīng)用程序,并且在線移動日常的桌面應(yīng)用程序(包括文字處理器和電子表格),能夠簡化開發(fā)并實現(xiàn)跨平臺支持的 JavaScript 庫將成為設(shè)計應(yīng)用程序架構(gòu)的必選技術(shù)。
這份關(guān)于 jQuery 的系列文章的第一篇介紹了 jQuery 語法,如何在您自己的 JavaScript 代碼中正確使用 jQuery,以及如何在結(jié)合使用其他庫時避免沖突。此外,本文還介紹了 jQuery 搜索和選擇語法,它們是其他 jQuery 功能的基礎(chǔ)。它使您可以簡單快捷地找到所需的頁面元素。文章也談到了如何遍歷搜索結(jié)果,使您可以逐個地處理元素。jQuery 的這兩個方面是本系列下一篇文章的基礎(chǔ),同時也是所有 jQuery 代碼的基礎(chǔ)。
最后介紹了一個演示應(yīng)用程序,它是一個富客戶端 Web 郵件應(yīng)用程序。在本文,您通過學(xué)到的 jQuery 知識創(chuàng)建了 Select All/Deselect All 復(fù)選框,并且僅需幾行代碼就可以創(chuàng)建一個在許多 Web 站點上都非常常見的小部件。
下一篇文章將把一些交互添加到這個示例 Web 應(yīng)用程序。您將學(xué)習(xí)如何處理頁面事件(單擊元素、按鈕點擊、組合框選擇等),如何從頁面上的元素獲取值,以及如何修改頁面上的標準 CSS 來更改顏色,布局等,而不需重新加載頁面。