Home Web Front-end JS Tutorial Detailed explanation of the difference between Jquery's $(selector).each() and $.each()

Detailed explanation of the difference between Jquery's $(selector).each() and $.each()

Jun 16, 2017 pm 04:20 PM
jquery selector the difference

We have all used the each function in Jqurey, and we all know that there are two ways to call each(), one is to call through $.each(), and the other is to call through $(selector).each() , so what’s the difference between them?

If you look at the Jquery source code, you will know that $.each() is the core implementation, $(selector).each() is the $.each() called, let’s first analyze $.each( ) source code (at the bottom):

The each (obj, callback, args) function receives 3 parameters: obj - the object or array to be traversed, callback - the callback function to be traversed and executed , args--the array specified by yourself (ignore it first).

The implementation of each method in jQuery uses the call method. The call method can set the context. First, in the following example, the effect of array each is the same. Why not call it directly?

You can change the pointer of this through call.

var testCall = function(obj, callback){
    callback.call(obj, 1);
}
Copy after login

testCall(["1. Change the pointer of this", "2. The function can be called internally through this"], function(index){ //Using the call method, you can directly access the call through this The object passed in as the first parameter.
alert(this[index]); //2. The function can be called through this });

Does not use the call method. this.

var test = function(obj, callback){
    callback(obj, 1);
}
Copy after login

test(["1. Change the pointer of this", "2. The function can be called through this inside the function"], function(index){ //Do not use call method, do not use this.
alert(this[index]); //undefined});

jQuery.each should be the this point modified by call;

$.each([1,2,3], function (index, item) {    console.log({index:index,value:item,_this:this});
});/*
  Object {index: 0, value: 1, _this: Number}
  Object {index: 1, value: 2, _this: Number}
  Object {index: 2, value: 3, _this: Number}
*/
Copy after login

I haven’t looked at the jQuery source code, use callback.call is a copycat and should be implemented in the same way.

var each = function(arr, callback){
  for( var index = 0 ; index < arr.length ; index++ ){
    callback.call(arr[index], index, arr[index]);
  }
}
each([1,2,3], function (index, item) {
    console.log({index:index,value:item,_this:this});
});/*
  Object {index: 0, value: 1, _this: Number}
  Object {index: 1, value: 2, _this: Number}
  Object {index: 2, value: 3, _this: Number}
*/
Copy after login

Note: this, if call is not used, this cannot be used in the callback function.

1. The case without args

Generally speaking, args are not commonly used, so we will not discuss the situation when if (args) is established first, that is, just look at the gray mark in the code part, this is also the core part of each() function

if(isArray) {
      for(; i < length; i++) {
        value = callback.call(obj[i], i, obj[i]);
        if(value === false) { break; }
      }
    }
Copy after login

If the object you want to traverse is an array type, enter this code block
 for loopTraverse Each element of the array , and then use the call method to execute obj[i].callback(i,obj[i]),
Therefore, when you write the callback function yourself, you should be aware that jquery will use arrays Each object in the callback method executes your callback function. The parameters passed are the index of the element in the array and the element. At the same time, this inside the callback method also points to the element;
The next line is to determine whether the callback function has returned a value. If the callback function returns false, break out of the array loop.

If the object you pass can also be traversed, the code is the same as the above array traversal

else {
      for(i in obj) {
          value = callback.call(obj[i], i, obj[i]);
          if(value === false) { break; }
        }
    }
Copy after login

If you pass the object, use for(x in y) to traverse Attributes of object ,
The principle is the same as above, except that it is replaced with the attribute x inside the object to execute the callback function, which is equivalent to obj.attr.callback(i,obj.attr);
Return If the function returns false, the loop operation will also end.

2. The situation with args

When calling each() with the third parameter, the following code block will be entered for analysis:  

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

In the same way, it will first determine whether the object you want to traverse is an array. If it is an array, traverse the element obj[i] of the array and execute obj[i].callback(args)
Note ! The parameter passed here is the args array you passed in. This is different from the args parameter without. That is to say, if you call the each function and pass in your own array parameter, the callbackParameters of the functionThe list is the args array you passed. Same as above for everything else.

$(selector).each(callback,args) function receives 2 parameters: callback--the callback function to be traversed and executed, args--the array specified by yourself. After understanding the $.each() function, $(selector).each is simple. Open the source code and find that the $.each() function is called inside $(selector).each. The source code is as follows:

each: function( callback, args ) {
      return jQuery.each( this, callback, args );
  },
Copy after login

You can see that when calling $.each(), the obj parameter is written as this, which is $(selector). This is the jquery selector returning a jqueryinternal object.  

Summary: The difference between $.each() and $(selector).each() is that the former can traverse all objects or arrays, while the latter is returned by the jquery selector jquery internal objects are traversed, the former is more powerful

The above is the detailed content of Detailed explanation of the difference between Jquery's $(selector).each() and $.each(). For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to set password protection for export PDF on PS How to set password protection for export PDF on PS Apr 06, 2025 pm 04:45 PM

Export password-protected PDF in Photoshop: Open the image file. Click "File"&gt; "Export"&gt; "Export as PDF". Set the "Security" option and enter the same password twice. Click "Export" to generate a PDF file.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Apr 05, 2025 pm 01:03 PM

The necessity of registering VueRouter in the index.js file under the router folder When developing Vue applications, you often encounter problems with routing configuration. Special...

How to use XPath to search from a specified DOM node in JavaScript? How to use XPath to search from a specified DOM node in JavaScript? Apr 04, 2025 pm 11:15 PM

Detailed explanation of XPath search method under DOM nodes In JavaScript, we often need to find specific nodes from the DOM tree based on XPath expressions. If you need to...

What is the difference between syntax for adding columns in different database systems What is the difference between syntax for adding columns in different database systems Apr 09, 2025 pm 02:15 PM

不同数据库系统添加列的语法为:MySQL:ALTER TABLE table_name ADD column_name data_type;PostgreSQL:ALTER TABLE table_name ADD COLUMN column_name data_type;Oracle:ALTER TABLE table_name ADD (column_name data_type);SQL Server:ALTER TABLE table_name ADD column_name data_

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

What are the different ways of promoting H5 and mini programs? What are the different ways of promoting H5 and mini programs? Apr 06, 2025 am 11:03 AM

There are differences in the promotion methods of H5 and mini programs: platform dependence: H5 depends on the browser, and mini programs rely on specific platforms (such as WeChat). User experience: The H5 experience is poor, and the mini program provides a smooth experience similar to native applications. Communication method: H5 is spread through links, and mini programs are shared or searched through the platform. H5 promotion methods: social sharing, email marketing, QR code, SEO, paid advertising. Mini program promotion methods: platform promotion, social sharing, offline promotion, ASO, cooperation with other platforms.

See all articles