JQuery. each usage and source code analysis, jquery. each source code

Source: Internet
Author: User

JQuery. each usage and source code analysis, jquery. each source code

The jQuery. each method is one of the core tools and methods of jQuery. It is a common sample method and can be used for sample object and array. Unlike the $ (). each () method of the jQuery object, this method can be used to sample any object. Two parameters are required.

Object: The object or array that needs to be repeated.

Callback: The callback function executed by each member/element.

The callback function has two parameters: the first is the object's member or array index, and the second is the corresponding variable or content. If you want to exit the each loop, the callback function returns false. Other return values are ignored.

Sample array, using both the element index and content. Example:

// Repeat the object and use both the member name and variable content. $. Each ([0, 1, 2], function (I, n) {alert ("Item #" + I + ":" + n) ;}); // example object, use both the member name and variable content. $. Each ({name: "John", lang: "JS"}, function (I, n) {alert ("Name:" + I + ", Value: "+ n );});

Of course, you can also directly use the instance to call

    $( 'div' ).each( function(i,n){        return i+n.text;    } )

In fact, in the source code, the instance (prototype) method is also a static method called. Therefore, to analyze the each method, you only need to analyze its static method. instance call is only a special case in the use of static methods.

// 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 );    },

In the prototype method, this object is passed in as the object to be traversed. the source code of the static method is as follows:

// 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;    },

There are not many things. First, we accept three parameters. At this time, we should note that in our frequently used manual, we generally use two parameters, however, in the source code, three parameters are acceptable. The third parameter is an array and will be passed in as a callback function parameter.

Declare several variables first. I, name, and length are prepared for the loop. isObj is used to distinguish whether the parameters to be convenient are arrays or objects, the object is determined by judging whether the parameter is a function or the length attribute does not exist. Other objects are processed by arrays or arrays of classes.

isObj = length === undefined || jQuery.isFunction( object );
This sentence is very short to use the priority of operators first run = operation in the execution | meta Calculation for not familiar with js operator order can refer to the http://www.cnblogs.com/yy-hh/p/4624792.html
In fact, such a judgment is not very accurate, just a rough distinction, such:
  var obj={length:'a'};  var isObj= obj.length=== undefined || jQuery.isFunction( obj );  alert(isObj);  //false

Then, it is determined by whether or not to add the third parameter. First, let's take a look at the case where no parameter is added, that is

} 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;                    }                }            }        }

Based on the isObj variable "differentiate" arrays and objects, use the for loop for arrays, and use the... in loop, each loop will execute a callback function and pass in the array or object key and value of the current loop. The call method is used here, the first parameter is the "this" of the function, that is, the value of the current loop is treated as the key and value or pointer and value after this, therefore, the second parameter for using the callback function in the loop is the same as using this. For example:

// The previous example $ ('div '). each (function (I, n) {return I + n. text;}) // equivalent to $ ('div '). each (function (I, n) {return I + this. text ;})

When the third parameter is added, the value passing method of the callback function is changed. The apply method is used to pass the parameter, this still points to the current value, but it only transmits the args, that is, the third parameter array. If there are many parameters in this array, then the callback function can use many parameters, note that the third object must be a js Acoustic Array and cannot be a class array or jQuery object. Otherwise, an error is reported because the apply method is not supported. If the callback function returns false, the loop will be skipped. For example, if we can only process the array with an odd subscript, we can execute "return false" in the callback function to determine whether the array is an even number.

return object;

Finally, the original object or array is returned.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.