Jquery's each method is Shared using examples

  • 2020-03-30 02:27:01
  • OfStack

For the jQuery object, it simply delegates the each method: pass the jQuery object as the first parameter to the jQuery each method. The jQuery object provides an each method that calls each of the child elements inside jQuery.

jQuery.prototype.each=function( fn, args ) { 
 return jQuery.each( this, fn, args ); 

Let's take a look at the implementation of each method provided by jQuery, jQuery. Each (obj, fn, arg)

The method has three parameters: obj, the object to operate on, fn, the function to operate on, and args.

Let's discuss it according to the ojb object:

1. Obj objects are arrays

The each method makes an fn function call to each of the subelements of the array until a call to one of the subelements returns false, that is, we can exit the call to the each method after the provided fn function is processed to satisfy certain conditions. When the each method provides an arg parameter, the fn function call passes in an arg parameter, otherwise: child element index, child element itself.

2. Obj objects are not arrays

The biggest difference between this method and 1 is that the fn method is carried out successively without considering the return value. In other words, all attributes of the obj object are called by the fn method, even if the fn function returns false. The arguments passed in by the call are similar to 1.

jQuery.each=function( obj, fn, args ) { 
    if ( args ) { 
       if ( obj.length == undefined ){ 
           for ( var i in obj ) 
             fn.apply( obj, args ); 
           for ( var i = 0, ol = obj.length; i < ol; i++ ) {
              if ( fn.apply( obj, args ) === false ) 
   } else { 
       if ( obj.length == undefined ) {
            for ( var i in obj ) 
               fn.call( obj, i, obj ); 
          for ( var i = 0, ol = obj.length, val = obj[0]; i < ol && fn.call(val,i,val) !== false; val = obj[++i] ){} 
  return obj; 

It is important to note that the specific method of calling fn in each method is not in the form of simple fn(I,val) or fn(args), but in the form of fn.call(val, I,val) or fn.apply(obj.args). This is the way most jQuery implementations work.

Related articles: