Home > Web Front-end > JS Tutorial > Detailed explanation of jquery.each usage and example code

Detailed explanation of jquery.each usage and example code

伊谢尔伦
Release: 2017-07-19 13:50:32
Original
1454 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 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.

Example of traversing an array, using both element index and content. For example:


//例遍对象,同时使用成员名称和变量内容。
$.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


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

. In fact, the instance (prototype) is in the source code. The method 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, in the source code There are three parameters that can be accepted, and the third parameter is an array, which 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 precise, 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 that


} 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

"distinguish" arrays and objects according to the isObj variable, use a for loop for arrays, and a for...in loop for objects, one for each loop The callback function will be executed once and the array or object key and value of the current loop will be passed 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 and the next two are keys. And value or pointer and value, so we use the second parameter of the callback function in the loop the same as using this. For example:


//刚才的例子
 $( &#39;p&#39; ).each( function(i,n){
    return i+n.text;
  } )
//等价于
 $( &#39;p&#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. The apply method is used to pass the parameters, and this points to The current value is still 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 can use as many parameters as possible. What needs to be noted here is that the third one must be in the form of a js original array and cannot be 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;
Copy after login

Finally return the original object or array, etc.

The above is the detailed content of Detailed explanation of jquery.each usage and example code. For more information, please follow other related articles on the PHP Chinese website!

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