先上例子,下面代碼的作用是:對每個選中的div元素,都給它們添加一個red類
$('div').each(function(index, elem){ $(this).addClass('red'); });
上面用的的.each,即jQuery.fn.each,其內部是通過jQuery.each實現的
jQuery.fn.each
先貼一下類官方API說明,非常簡單,只有兩點需要注意
- 上文例子里的$(this).addClass('red'),其中,
this
指的是當前操作的dom元素 - each中傳入的方法,可以返回任意值,當返回的值為false時,跳出當前循環操作
/** * @description 對jQuery對象中,匹配的的每個dom元素執行一個方法 * @param {Number} index 當前處理元素在集合中的位置 * @param {DOMElement} Element 當前處理的dom元素 */ .each( function(index, Element) )
下面舉兩個簡單的例子
例子一:
給頁面所有的div元素添加red類
$('div').each(function(index, elem){ $(this).addClass('red'); });
例子二
給頁面前5個div元素添加red類
$('div').each(function(index, elem){ if(index>=5) return false; // 跳出循環 $(this).addClass('red'); });
如上,用法挺簡單,不贅述,詳細可查看 http://api.jquery.com/each/
源碼
內部是通過jQuery.each實現的,下面就講下jQuery.each的源碼,講完jQuery.each的源碼,jQuery.fn.each的源碼就很簡單了
//略。。。
jQuery.each
同樣是先上一個簡單的例子
$.each([52, 97], function(index, value) { alert(index + ': ' + value + ':' + this); });
輸出內容如下:
0: 52-52 1: 97-97
類官方API說明
同樣是有兩個注意點
- 上面例子中的
this
,是集合中的元素,即下面的valueOfElement
- 在callback中返回
false
,可以跳出循環
/** * @description 對集合(數組或對象)中的每個元素,執行某個操作 * @param {Number|String} indexInArray 元素在集合中對應的位置(如集合為數組,則為數字;如集合為對象,則為鍵值) * @param {AnyValue} valueOfElement 集合中的元素 */ jQuery.each( collection, callback(indexInArray, valueOfElement) )
例子一
$.each( ['one,'two','three', 'four'], function(index, value){
if(index >= 2) return false;
alert( "Index:" + index + ", value: " + value );
});
例子二
從官網直接copy來的例子,湊合着看
$.each( { name: "John", lang: "JS" }, function(k, v){ alert( "Key: " + k + ", Value: " + v ); });
源碼
// args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); // obj是不是類似數組的對象,比如 {'0':'hello', '1':'world', 'length':2},其實就是為jQuery對象服務啦 if ( args ) { // args,其實沒發現這個參數有什么實際作用~~直接跳過看else里面的內容即可,除了callback傳的參數不同外無其他區別 if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { // 處理數組 for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { // 處理對象 for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); // value 為callback的返回值 if ( value === false ) { // 注意這里,當value===false的時候,直接跳出循環了 break; } } } } return obj; },
遲到的jQuery.fn.each源碼
的確很簡單,只要理解了jQuery.each應該就沒問題了,沒什么好講的~
each: function( callback, args ) { return jQuery.each( this, callback, args ); },
結束語
與jQuery.extend、jQuery.fn.extend一樣,雖然 jQuery.each、jQuery.fn.each代碼很簡單,但也扮演了相當重要的作用,jQuery里大量用到了這兩個方法,舉例:
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); });
所以,少年好好掌握each吧~~