在 DOM 操作中,遍歷是家常便飯。jQuery 為此準備了一套豐富的遍歷函數,涵蓋了篩選、查找與串聯元素等各類需求。掌握它們,能讓你的選擇器操作事半功倍。
函數 描述 .add() 將元素添加到匹配元素的集合中。 .andSelf() 把堆棧中之前的元素集添加到當前集合中。 .children() 獲得匹配元素集合中每個元素的所有子元素。 .closest() 從元素本身開始,逐級向上級元素匹配,並返回最先匹配的祖先元素。 .contents() 獲得匹配元素集合中每個元素的子元素,包括文本和注釋節點。 .each() 對 jQuery 對象進行迭代,為每個匹配元素執行函數。 .end() 結束當前鏈中最近的一次篩選操作,並將匹配元素集合返回到前一次的狀態。 .eq() 將匹配元素集合縮減為位於指定索引的新元素。 .filter() 將匹配元素集合縮減為匹配選擇器或匹配函數返回值的新元素。 .find() 獲得當前匹配元素集合中每個元素的後代,由選擇器進行篩選。 .first() 將匹配元素集合縮減為集合中的第一個元素。 .has() 將匹配元素集合縮減為包含特定元素的後代的集合。 .is() 根據選擇器檢查當前匹配元素集合,如果存在至少一個匹配元素,則返回 true。 .last() 將匹配元素集合縮減為集合中的最後一個元素。 .map() 把當前匹配集合中的每個元素傳遞給函數,產生包含返回值的新 jQuery 對象。 .next() 獲得匹配元素集合中每個元素緊鄰的同輩元素。 .nextAll() 獲得匹配元素集合中每個元素之後的所有同輩元素,由選擇器進行篩選(可選)。 .nextUntil() 獲得每個元素之後所有的同輩元素,直到遇到匹配選擇器的元素為止。 .not() 從匹配元素集合中刪除元素。 .offsetParent() 獲得用於定位的第一個父元素。 .parent() 獲得當前匹配元素集合中每個元素的父元素,由選擇器篩選(可選)。 .parents() 獲得當前匹配元素集合中每個元素的祖先元素,由選擇器篩選(可選)。 .parentsUntil() 獲得當前匹配元素集合中每個元素的祖先元素,直到遇到匹配選擇器的元素為止。 .prev() 獲得匹配元素集合中每個元素緊鄰的前一個同輩元素,由選擇器篩選(可選)。 .prevAll() 獲得匹配元素集合中每個元素之前的所有同輩元素,由選擇器進行篩選(可選)。 .prevUntil() 獲得每個元素之前所有的同輩元素,直到遇到匹配選擇器的元素為止。 .siblings() 獲得匹配元素集合中所有元素的同輩元素,由選擇器篩選(可選)。 .slice() 將匹配元素集合縮減為指定范圍的子集。
each 的用法
1. 遍歷數組
var arr = [ "one", "two", "three", "four"]; $.each(arr, function(){ alert(this); }); //上面這個each輸出的結果分別為:one,two,three,four var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]] $.each(arr1, function(i, item){ alert(item[0]); }); //其實arr1為一個二維數組,item相當於取每一個一維數組, //item[0]相對於取每一個一維數組裡的第一個值 //所以上面這個each輸出分別為:1 4 7 var obj = { one:1, two:2, three:3, four:4}; $.each(obj, function(i) { alert(obj[i]); }); //這個each就有更厲害了,能循環每一個屬性 //輸出結果為:1 2 3 4 2. 遍歷 DOM 元素
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("li").each(function(){ alert($(this).text()) }); }); }); </script> </head> <body> <button>輸出每個列表項的值</button> <ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul> </body> </html> 點擊按鈕後,會依次彈出 Coffee、Milk、Soda。
3. each 與 map 的對比
下面的例子用來獲取每個複選框的 ID 值。先看 each 方法——定義一個空數組,通過 each 把 ID 逐一 push 進去,最後拼接成字符串:
$(function(){ var arr = []; $(":checkbox").each(function(index){ arr.push(this.id); }); var str = arr.join(","); alert(str); }) 而 map 方法則顯得更為簡潔,它會把每次 return 的值自動收集成 jQuery 對象,再借助 get() 轉為原生數組,最後 join 拼接:
$(function(){ var str = $(":checkbox").map(function() { return this.id; }).get().join(); alert(str); }) 當你需要一個由元素值組成的數組時,map 往往更省事。
4. jQuery 中使用 each
遍歷數組並同時拿到索引與內容(i 為索引,n 為內容):
$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); }); 遍歷對象,同時拿到成員名稱與對應的值:
$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); }); 遍歷 DOM 元素,這裡以隱藏的 input 表單元素為例。假設 DOM 中有如下代碼:
<input name="aaa" type="hidden" value="111" /> <input name="bbb" type="hidden" value="222" /> <input name="ccc" type="hidden" value="333" /> <input name="ddd" type="hidden" value="444"/>
用 each 遍歷時:
$.each($("input:hidden"), function(i,val){ alert(val); //輸出[object HTMLInputElement],因為它是一個表單元素。 alert(i); //輸出索引為0,1,2,3 alert(val.name); //輸出name的值 alert(val.value); //輸出value的值 }); 5. 在 each 中通過 this 查找元素
例如讓「回復」二字只在鼠標懸停時顯示:
<ol class="commentlist"> <li class="comment"> <div class="comment-body"> <p>嗨,第一層評論</p> <div class="reply"> <a href="#" class=".comment-reply-link">回復</a> </div> </div> <ul class="children"> <li class="comment"> <div class="comment-body"> <p>第二層評論</p> <div class="reply"> <a href="#" class=".comment-reply-link">回復</a> </div> </div></li> </ul> </li> </ol>
對應的 JS:
$("div.reply").hover(function(){ $(this).find(".comment-reply-link").show(); },function(){ $(this).find(".comment-reply-link").hide(); }); 再如判斷每道單選題是否都已作答:
<ul id="ulSingle"> <li class="liStyle"> 1. 阿斯頓按時<label id="selectTips" style="display: none" class="fillTims">請選擇</label> <!--begin選項--> <ul> <li class="liStyle2"> <span id="repSingle_repSingleChoices_0_labOption_0">A </span>.阿薩德發<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl00$hidID" id="repSingle_repSingleChoices_0_hidID_0" value="1" /> <input id="repSingle_repSingleChoices_0_cheSingleChoice_0" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl00$cheSingleChoice" /></li> <li class="liStyle2"> <span id="repSingle_repSingleChoices_0_labOption_1">B </span>.阿薩德發<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl01$hidID" id="repSingle_repSingleChoices_0_hidID_1" value="2" /> <input id="repSingle_repSingleChoices_0_cheSingleChoice_1" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl01$cheSingleChoice" /></li> <li class="liStyle2"> <span id="repSingle_repSingleChoices_0_labOption_2">C </span>.阿斯頓<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl02$hidID" id="repSingle_repSingleChoices_0_hidID_2" value="3" /> <input id="repSingle_repSingleChoices_0_cheSingleChoice_2" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl02$cheSingleChoice" /></li> </ul> <!--end選項--> <br /> </li> </ul>
配套的驗證代碼:
//驗證單選題是否選中 $("ul#ulSingle>li.liStyle").each(function (index) { //選項個數 var count = $(this).find("ul>li>:checkbox").length; var selectedCount = 0 for (var i = 0; i < count; i++) { if ($(this).find("ul>li>:checkbox:eq(" + i + ")").attr("checked")) { selectedCount++; break; } } if (selectedCount == 0) { $(this).find("label#selectTips").show(); return false; } else { $(this).find("label#selectTips").hide(); } }) 6. 官方解釋
jQuery.each(object, [callback]) 是一個通用遍歷方法,可用於遍歷對象和數組。與遍歷 jQuery 對象的 $().each() 不同,它能夠遍歷任意對象。回調函數接收兩個參數:第一個是對象的成員或數組的索引,第二個是對應的值或內容。若想提前結束循環,只需讓回調函數返回 false,其他返回值都會被忽略。