Home > Web Front-end > JS Tutorial > body text

jQuery source code analysis jQuery.fn.each and jQuery.each usage_jquery

WBOY
Release: 2016-05-16 16:18:11
Original
1169 people have browsed it

The example in this article describes the usage of jQuery.fn.each and jQuery.each in jQuery source code analysis. Share it with everyone for your reference. The specific analysis is as follows:

Let’s start with the example. The function of the following code is to add a red class to each selected div element

Copy code The code is as follows:
$('div').each(function(index, elem){

$(this).addClass('red');
}
});

The .each used above is jQuery.fn.each, which is internally implemented through jQuery.each

Copy code The code is as follows:
jQuery.fn.each

First, let’s post the official API description. It’s very simple. There are only two points to note
$(this).addClass('red') in the above example, where this refers to the dom element currently being operated
The method passed in each can return any value. When the returned value is false, jump out of the current loop operation
Copy code The code is as follows:
/**

* @description Execute a method for each matching dom element in the jQuery object

* @param {Number} index The position of the currently processed element in the collection

* @param {DOMElement} Element The currently processed dom element

*/
.
.each( function(index, Element) )

Here are two simple examples

Example 1:

Add red class to all div elements on the page

Copy code The code is as follows:
$('div').each(function(index, elem){

$(this).addClass('red');
}
});

Example 2

Add red class to the first 5 div elements on the page

Copy code The code is as follows:
$('div').each(function(index, elem){

If(index>=5) return false; // Break out of the loop
$(this).addClass('red');
}
});

As above, the usage is quite simple, so I won’t go into details. For details, please check http://api.jquery.com/each/

The internal source code is implemented through jQuery.each. Let’s talk about the source code of jQuery.each. After talking about the source code of jQuery.each, the source code of jQuery.fn.each is very simple

jQuery.each:

Let’s take a simple example first

Copy code The code is as follows:
$.each([52, 97], function(index, value) {
alert(index ': ' value ':' this);
}
});

The output content is as follows:

0: 52-52
1
1: 97-97

Class official API description

There are also two points to note

This in the above example is the element in the collection, that is, the following valueOfElement
Return false in the callback to break out of the loop

Copy code The code is as follows:
/**

* @description Perform an operation on each element in the collection (array or object)

* @param {Number|String} indexInArray The corresponding position of the element in the collection (if the collection is an array, it is a number; if the collection is an object, it is a key value)

* @param {AnyValue} valueOfElement The element in the collection

*/
j
jQuery.each( collection, callback(indexInArray, valueOfElement) )


Example 1
Copy code The code is as follows:
$.each( ['one,'two','three', 'four '], function(index, value){

If(index >= 2) return false;

​​ alert( "Index:" index ", value: " value );
}
});

Example 2

The example is copied directly from the official website, just make do with it

Copy code The code is as follows:
$.each( { name: "John", lang: "JS" }, function(k, v){

​​ alert( "Key: " k ", Value: " v );
}
});

Source code:
Copy code The code is as follows:
// args is for internal usage only
e
each: function( obj, callback, args ) {

var value,

i = 0,

length = obj.length,

isArray = isArraylike( obj ); // Is obj an array-like object, such as {'0':'hello', '1':'world', 'length':2}, which actually serves jQuery objects

If ( args ) { // args, I actually didn’t find any actual effect of this parameter~~ Just skip and look at the content in else. There is no other difference except that the parameters passed in the callback are different
           if ( isArray ) {
for ( ; i < length; i ) {
                     value = callback.apply( obj[ i ], args );
If ( value === false ) {
break;
                }
            }
         } else {
for ( i in obj ) {
                     value = callback.apply( obj[ i ], args );
If ( value === false ) {
break;
                }
            }
}
// A special, fast, case for the most common use of each
} else {
           if ( isArray ) {                                                                                                                                                                                                               for ( ; i < length; i ) {
                   value = callback.call( obj[ i ], i, obj[ i ] );
If ( value === false ) {
break;
                }
            }
} Else {// Treatment objects
for ( i in obj ) {
                    value = callback.call( obj[ i ], i, obj[ i ] ); // value is the return value of callback
If (value === false) {// Note here, when value === false, jump out of the cycle directly
break;
                }
            }
}
}
Return obj;
}
},



Late jQuery.fn.each source code:

It’s really simple. As long as you understand jQuery.each, you should be fine. There’s nothing to talk about~

Copy code The code is as follows:
each: function( callback, args ) {

Return jQuery.each( this, callback, args );
}
},


Conclusion

Same as jQuery.extend and jQuery.fn.extend, although the codes of jQuery.each and jQuery.fn.each are very simple, they also play a very important role. These two methods are widely used in jQuery, for example:

Copy code The code is as follows:
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split( " "), function(i, name) {

Class2type[ "[object " name "]" ] = name.toLowerCase();
}
});

So, master each!

I hope this article will be helpful to everyone’s jQuery programming.

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