Home Web Front-end JS Tutorial jQuery source code analysis jQuery.fn.each and jQuery.each usage_jquery

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

May 16, 2016 pm 04:18 PM
jquery analyze Source code usage

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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation and usage introduction of MySQL ISNULL function Detailed explanation and usage introduction of MySQL ISNULL function Mar 01, 2024 pm 05:24 PM

The ISNULL() function in MySQL is a function used to determine whether a specified expression or column is NULL. It returns a Boolean value, 1 if the expression is NULL, 0 otherwise. The ISNULL() function can be used in the SELECT statement or for conditional judgment in the WHERE clause. 1. The basic syntax of the ISNULL() function: ISNULL(expression) where expression is the expression to determine whether it is NULL or

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to display the source code of PHP code in the browser without being interpreted and executed? How to display the source code of PHP code in the browser without being interpreted and executed? Mar 11, 2024 am 10:54 AM

How to display the source code of PHP code in the browser without being interpreted and executed? PHP is a server-side scripting language commonly used to develop dynamic web pages. When a PHP file is requested on the server, the server interprets and executes the PHP code in it and sends the final HTML content to the browser for display. However, sometimes we want to display the source code of the PHP file directly in the browser instead of being executed. This article will introduce how to display the source code of PHP code in the browser without being interpreted and executed. In PHP, you can use

PHP source code error: solving index error problem PHP source code error: solving index error problem Mar 10, 2024 am 11:12 AM

PHP source code error: To solve the index error problem, specific code examples are needed. With the rapid development of the Internet, developers often encounter various problems when writing websites and applications. Among them, PHP is a popular server-side scripting language, and its source code errors are one of the problems that developers often encounter. Sometimes, when we try to open the index page of a website, various error messages will appear, such as "InternalServerError", "Unde

A comprehensive guide to learning and applying golang framework source code A comprehensive guide to learning and applying golang framework source code Jun 01, 2024 pm 10:31 PM

By understanding the Golang framework source code, developers can master the essence of the language and expand the framework's functions. First, get the source code and become familiar with its directory structure. Second, read the code, trace the execution flow, and understand dependencies. Practical examples show how to apply this knowledge: create custom middleware and extend the routing system. Best practices include learning step-by-step, avoiding mindless copy-pasting, utilizing tools, and referring to online resources.

Analyze whether Tencent's main programming language is Go Analyze whether Tencent's main programming language is Go Mar 27, 2024 pm 04:21 PM

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

See all articles