jQuery的操作往往是分两步
1,获取元素集合(选择器)
2,操作元素集合
而第二步操作元素集合的主要方法就是jQuery.each。查看源码,我们发现jQuery.each及this.each分别调用了27次和31次。可见它是多么的重要。
这篇将分析下jQuery.each及this.each方法。看看他们如何与jQuery.extend一起扩展jQuery库。最后我会给zChain.js加上each方法。
部分源码如下
代码如下:
jQuery.fn = jQuery.prototype = {
...
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
...
}
jQuery.extend({
...
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
...
});
以上可看出,
1,jQuery().each是直接挂在jQuery.prototype(jQuery.fn)上的,因此每个jQuery对象都包含each方法。
2,jQuery.each是通过jQuery.extend({})方式扩展的。前面已经说过,通过这种方式扩展的方法将挂在function jQuery上,即为jQuery类的静态方法。
3,jQuery().each方法中只有一句:return jQuery.each( this, callback, args )。即jQuery对象的each方法实现上其实就是调用jQuery静态的jQuery.each。因此jQuery.each才是关键所在。
下面详细分析jQuery.each,它有三个参数object, callback, args。
1,object可以为数组(Array),对象(Object),甚至是函数类型(Functoin);
2,callback是回调函数,类型为function;
3,args为jQuery库自身使用,使用者不会用到该参数,这里暂不讨论该参数情况。
函数中第一句定义必要的变量
代码如下:
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
length=object.length很好理解,有三种情况length不为undefined
1, object为数组类型(Array)时,数组具有length属性;
2, object为函数类型(Functoin)时,length为该函数定义的参数个数,如果该函数没有定义参数,length为0;
3, 具有length属性的object伪数组(如:arguments,HTMLCollection,NodeList等)。