| 方法 | 類型 | 用途 | 回調參數 |
|---|---|---|---|
$().each() | jQuery 物件實例方法 | 遍歷 jQuery 物件集合(DOM 元素) | function(index, element):index 為索引,element 為原生 DOM |
$.each() | jQuery 全域靜態方法 | 遍歷任意陣列、物件(JSON)、類陣列 | function(key, value):key 為索引或屬性名,value 為對應值 |
搭配 $.getJSON 取得資料後遍歷:
$.getJSON('data.json', function(data){
// data 已自動解析為 JS 物件/陣列
$.each(data, function(key, entry){
// key 為 JSON 的鍵(如 "term"),entry 為對應的值物件
var html = entry['term']; // 取得 entry 裡的 term 欄位
// 處理 html...
});
});
$.each(data, function(entryIndex, entry){ var html = entry['term']; }),讓人以為 entryIndex 是數字索引。實則 entryIndex 就是 JSON 的 鍵名(如 "term"),作者直接用鍵名取值才看不出差異。$().each 遍歷「元素」,索引是數字;$.each 遍歷「資料」,索引是鍵(Key)。$('.item').each(function(index, el){
// this === el(原生 DOM)
console.log(index, $(this).text());
});
false 相當於 break(跳出整個 each)。true 相當於 continue(跳過本次進入下一次)。$.each(arr, function(i, v){
if (v === 'stop') return false; // break
if (v === 'skip') return true; // continue
console.log(v);
});
$().each()。$.each()。