标签:jquery
$(function(){ var $div = $(‘div‘ ); var args = [":参数" ] $div.each( function(){ alert( this.id + arguments[0]); return false ; },args); //只弹出一次 div1:参 数 });
JQuery.each(obj, callback, args)的源码也比较简单,见注释 // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); //如果有参数 if ( args ) { //如果是类数组 //则用使用obj[下标]的方式访问迭代的元素 if ( isArray ) { for ( ; i < length; i++ ) { //绑定回调函数的执行作用域,即回调函数使用this时,this指向当前迭代的元素,回调函数的参数为传入的args value = callback.apply( obj[ i ], args ); //如果返回false,退出迭代 if ( value === false ) { break; } } //如果不是是类数组 //则用for-in迭代 } 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 //和上个分支的处理一样这 //只是没有传入args //大量的重复代码是为了更少的逻辑判断,匹配最长用的方式,使处理更快 } 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 ] ); if ( value === false ) { break; } } } } //返回要迭代的obj,通常是jquery对象 return obj; },
var $div = $(‘div‘ ); $div.map( function (){ return this .parentNode; }).each( function (){ alert( this .tagName); //弹出两次 BODY });
map: function( callback ) { return this .pushStack( jQuery.map( this, function ( elem, i ) { return callback.call( elem, i, elem ); })); },
map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), //存放结果的数组 ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { //嗲用callback绑定执行作用域为当前迭代元素 value = callback( elems[ i ], i, arg ); if ( value != null ) { //将返回值推入数组末尾 ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); },
标签:jquery
原文地址:http://blog.csdn.net/songzheng_741/article/details/24699249