Home  >  Article  >  Web Front-end  >  Detailed explanation of jQuery.each usage_jquery

Detailed explanation of jQuery.each usage_jquery

WBOY
WBOYOriginal
2016-05-16 15:51:101180browse

The jQuery.each method is one of the core tool methods of jQuery. It is a general iteration method that can be used to iterate objects and arrays. Unlike the $().each() method, which iterates over jQuery objects, this method can be used to iterate over any object. Usually requires two parameters

object: The object or array that needs to be traversed.

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

The callback function has two parameters: the first is the member of the object or the index of the array, and the second is the corresponding variable or content. If you need to exit the each loop, you can make the callback function return false, and other return values ​​will be ignored.

Loop through an array, using both element index and content. Examples are as follows:

//例遍对象,同时使用成员名称和变量内容。

$.each( [0,1,2], function(i, n){
 alert( "Item #" + i + ": " + n );
});
//例遍对象,同时使用成员名称和变量内容。

$.each( { name: "John", lang: "JS" }, function(i, n){
 alert( "Name: " + i + ", Value: " + n );
});

Of course, you can also use the instance call directly

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

In fact, the instance (prototype) method in the source code is also a static method called, so to analyze each method, you only need to analyze its static method. Instance calling is just a special case of using 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, pass this object directly as the object to be traversed. The following is the source code of the static method

// 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 of all, it accepts 3 parameters. At this time, we should pay attention to the fact that the manuals we often use usually write two parameters. We generally use two parameters, but in fact, in the source code, There are 3 parameters that can be accepted, the third parameter is an array, which will be passed in as a parameter of the callback function.

First declare a few variables. i, name and length are to prepare for the loop. isObj is to distinguish whether the parameter to be convenient is an array or an object. It can be judged whether it is an object by judging whether the parameter is a function or the length attribute does not exist. , the rest are handled as arrays or array-like.

isObj = length === undefined || jQuery.isFunction( object );
This sentence is written very concisely and uses the precedence order of operators to execute first ===

In fact, this kind of judgment is not very precise, it is just a rough distinction, such as:

 var obj={length:'a'};
 var isObj= obj.length=== undefined || jQuery.isFunction( obj );
 alert(isObj); //false

Then the distinction is based on whether the third parameter is added. Let’s first look at the situation without adding it, which 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;
          }
        }
      }
    }

"Distinguish" arrays and objects based on the isObj variable. Use a for loop for arrays and a for...in loop for objects. Each time the loop is executed, a callback function will be executed and the current loop array or object key and value will be executed. Pass in, the call method used here, the first parameter is the "this" of the function, that is, the value of the current loop is used as this, the next two are key and value or pointer and value, so we use the callback function in the loop The second parameter is the same as using this. For example:

//刚才的例子
 $( 'div' ).each( function(i,n){
    return i+n.text;
  } )
//等价于
 $( 'div' ).each( function(i,n){
    return i+this.text;
  } )

For the case where the third parameter is added, the value transfer method of the callback function is changed. The apply method is used to transfer parameters. This still points to the current value, but args is the third parameter. The array is passed in, and the callback function can use as many parameters as the array has. What needs to be noted here is that the third one must be a js original array format and cannot be a class array or jQuery object, otherwise an error will be reported because the apply method is not supported. If the callback function returns false, the loop will be skipped. For example, we can only process the odd-numbered subscript array, and when it is judged to be an even-numbered item, just execute return false in the callback function

return object;

Finally return the original object or array, etc.

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn