Home > Web Front-end > JS Tutorial > Detailed explanation of jQuery.each usage

Detailed explanation of jQuery.each usage

高洛峰
Release: 2016-12-29 11:06:36
Original
1175 people have browsed it

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 two parameters are required

object: the object or array 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.

Example of traversing an array, using both element index and content. An example is 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 );
});
Copy after login

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

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

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 );
  },
Copy after login

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;
  },
Copy after login

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 there are 3 parameters that can be accepted in the source code. The third parameter is an array and will be passed in as a parameter of the callback function.

First declare several 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, by judging whether the parameter is a function or the length attribute does not exist. The judgment is that it is an object, and the others are processed as arrays or array-like objects.

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

In fact, this is the case The judgment is not very accurate, it is just a rough distinction, for example:

var obj={length:&#39;a&#39;};
var isObj= obj.length=== undefined || jQuery.isFunction( obj );
alert(isObj); //false
Copy after login

Then the distinction is based on whether the third parameter is added. First check if it is not added. The situation 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;
          }
        }
      }
    }
Copy after login

"Differentiate" arrays and objects according to the isObj variable, use a for loop for arrays, and a for...in loop for objects, each time Once the loop is complete, a callback function will be executed and the array or object key and value of the current loop will be passed in. In the call method used here, the first parameter is the "this" of the function, which means that the value of the current loop is used as the next two characters of this. One is a key and value or a pointer and value, so the second parameter of the callback function we use in the loop is the same as using this. For example:

//刚才的例子
 $( &#39;div&#39; ).each( function(i,n){
    return i+n.text;
  } )
//等价于
 $( &#39;div&#39; ).each( function(i,n){
    return i+this.text;
  } )
Copy after login

For the case where the third parameter is added, the value-passing method of the callback function is changed, and the apply method is used to pass the parameters. , this still points to the current value, but args, which is the third parameter array, is passed in. As many parameters as there are in this array, the callback function has as many parameters as it can use. What needs to be noted here is that the third one must be the js original sound array. The form cannot be an array-like 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. If we can judge that it is an even number, just execute return false in the callback function.

return object;
Copy after login

Finally return Original object or array, etc.

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

For more detailed articles on the use of jQuery.each, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template