jQuery 並沒有名為 foreach 的方法,但 each() 就是它用來遍歷元素集合的等價工具,用法非常直覺。
以下是一個表單的 HTML 結構:
<form id="input_iForm" action="...">
<input type="text" class="input_w150" vili="true" onkeyup="formatBankNo(this)"/>
<input type="text" class="input_w150" vili="true" onkeyup="formatBankNo(this)"/>
<input type="text" class="input_w150" vili="true" onkeyup="formatBankNo(this)"/>
</form>
用 each 遍歷頁面上所有 input:
$("input:text").each(function(index){
alert(index);//迴圈的下標值,從 0 開始
alert(this.value); alert($(this).attr("type")); //內建屬性可用 this(DOM)直接取值
alert($(this).attr("vili")); //自訂屬性則需用 attr(jQuery)取值
});
這裡有個小眉角:內建的屬性(如 value、type)可以用原生 DOM 的 this 直接取得,而像 vili 這種自訂屬性,就必須透過 jQuery 的 attr 方法來讀取。
each 也常搭配 Ajax 使用,例如把回傳的資料轉成日曆事件:
$.ajax({
url: '...getMonthRecordLs.action',
dataType: 'json',
success: function(data) {
var events = [];
$(data).each(function(i,val) {
events.push({
id: val.sc_id,
title: val.sc_planemp,
start: new Date(val.sc_date),
color: val.sc_classes=='1'?'':'#993300'
});
});
callback(events);
}
});
不論是遍歷 DOM 元素還是陣列資料,each() 都能勝任,是 jQuery 開發中相當核心的語法之一。