search
HomeWeb Front-endFront-end Q&AWhat is a callback function in jquery

What is a callback function in jquery

Nov 17, 2022 pm 08:29 PM
javascriptjquery

In jquery, the callback function is a function that is passed as a parameter. Function A is passed as a parameter (function reference) to another function B, and this function B executes function A, then function A is called a callback function; if there is no name (function expression), it is called an anonymous callback function. The use of callback functions can greatly improve the efficiency of programming, which makes it widely used in modern programming.

What is a callback function in jquery

The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.

Functions are also objects

If you want to understand the callback function, you must first clearly understand the rules of the function . In JavaScript, functions are weird, but they are indeed objects. To be precise, a function is a Function object created using the Function() constructor. The Function object contains a string that contains the JavaScript code of the function. If you are coming from C or Java, this may seem strange. How can the code be a string? But with javascript, this is commonplace. The distinction between data and code is blurry.

//可以这样创建函数
var fn = new Function("arg1", "arg2", "return arg1 * arg2;");
fn(2, 3); //6

One advantage of doing this is that you can pass code to other functions, or you can pass regular variables or objects (because the code is literally just an object).

Passing functions as callbacks

It’s easy to pass a function as a parameter.

function fn(arg1, arg2, callback){
 var num = Math.ceil(Math.random() * (arg1 - arg2) + arg2);
 callback(num);  //传递结果
}

fn(10, 20, function(num){
 console.log("Callback called! Num: " + num); 
});    //结果为10和20之间的随机数

Maybe this seems cumbersome, or even a bit stupid, why not return the results normally? But when you have to use a callback function, you may not think so!

Traditional functions input data in the form of parameters and use return statements to return values. Theoretically, there is a return statement at the end of the function, which is structurally: an input point and an output point. This is easier to understand. A function is essentially a mapping of the implementation process between input and output.

However, when the function implementation process is very long, do you choose to wait for the function to complete processing, or use a callback function for asynchronous processing? In this case, it becomes crucial to use callback functions, for example: AJAX requests. If you use a callback function for processing, the code can continue to perform other tasks without waiting in vain. In actual development, asynchronous calls are often used in JavaScript, and it is even highly recommended here!

Below is a more comprehensive example of using AJAX to load an XML file, and uses the call() function to call the callback function in the context of the requested object.

function fn(url, callback){
 var httpRequest;    //创建XHR
 httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() :   //针对IE进行功能性检测
    window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : undefined;
 
 httpRequest.onreadystatechange = function(){
  if(httpRequest.readystate === 4 && httpRequest.status === 200){  //状态判断
   callback.call(httpRequest.responseXML); 
  }
 };
 httpRequest.open("GET", url);
 httpRequest.send();
}

fn("text.xml", function(){    //调用函数
 console.log(this);   //此语句后输出
});

console.log("this will run before the above callback.");  //此语句先输出

We request asynchronous processing, which means that when we start the request, we tell them to call our function when they are completed. In actual situations, the onreadystatechange event handler must also consider the situation of request failure. Here we assume that the xml file exists and can be successfully loaded by the browser. In this example, the asynchronous function is assigned to the onreadystatechange event and therefore will not be executed immediately.

Ultimately, the second console.log statement is executed first because the callback function is not executed until the request is completed.

The above example is not easy to understand, so take a look at the following example:

 function foo(){
 var a = 10;
 return function(){
  a *= 2;
  return a;  
 }; 
}
var f = foo();
f(); //return 20.
f(); //return 40.

  函数在外部调用,依然可以访问变量a。这都是因为javascript中的作用域是词法性的。函数式运行在定义它们的作用域中(上述例子中的foo内部的作用域),而不是运行此函数的作用域中。只要f被定义在foo中,它就可以访问foo中定义的所有的变量,即便是foo的执行已经结束。因为它的作用域会被保存下来,但也只有返回的那个函数才可以访问这个保存下来的作用域。返回一个内嵌匿名函数是创建闭包最常用的手段。

回调是什么?

看维基的 Callback_(computer_programming) 条目:

In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.

jQuery文档How jQuery Works#Callback_and_Functio...条目:

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes. Another important thing to know is how to properly pass the callback. This is where I have often forgotten the proper syntax.

百科:回调函数

回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

因此,回调本质上是一种设计模式,并且jQuery(包括其他框架)的设计原则遵循了这个模式。

在JavaScript中,回调函数具体的定义为:函数A作为参数(函数引用)传递到另一个函数B中,并且这个函数B执行函数A。我们就说函数A叫做回调函数。如果没有名称(函数表达式),就叫做匿名回调函数。

因此callback 不一定用于异步,一般同步(阻塞)的场景下也经常用到回调,比如要求执行某些操作后执行回调函数。

例子
一个同步(阻塞)中使用回调的例子,目的是在func1代码执行完成后执行func2。

var func1=function(callback){
  //do something.
  (callback && typeof(callback) === "function") && callback();
}

func1(func2);
  var func2=function(){
}

异步回调的例子:

$(document).ready(callback);

$.ajax({
 url: "test.html",
 context: document.body
}).done(function() { 
 $(this).addClass("done");
}).fail(function() { alert("error");
}).always(function() { alert("complete"); 
});
/**
注意的是,ajax请求确实是异步的,不过这请求是由浏览器新开一个线程请求,当请求的状态变更时,如果先前已设置回调,这异步线程就产生状态变更事件放到 JavaScript引擎的处理队列中等待处理。*/

回调什么时候执行

回调函数,一般在同步情境下是最后执行的,而在异步情境下有可能不执行,因为事件没有被触发或者条件不满足。

为什么会需要回调函数

把一个函数作为参数传入到我们的主函数中,让这个函数按照我们的想法顺序进行执行。

我们希望能够在弹出提示信息之后,在我们进行点击确定之后,再执行一个函数内容,这个时候就会用到回调。

因为在程序是非堵塞的,弹出消息之后,在我们还没在弹出框里面进行点击确认或者选择的时候,程序已经执行下面的语句了;

这样我们就没有选择权了,不符合用户习惯,所以我们采用回调函数的方式;

采用了回调函数之后,我们就把callback与主函数体合二为一了,就会是顺序执行了,就可以进行选择和点击确认了。

分开写会导致不能对弹出框进行确认

回调函数作为参数加入到主函数中,可以使得回调在主函数中进行顺序执行,弹出框也就可以正常了。

回调函数的使用场合

资源加载:动态加载js文件后执行回调,加载iframe后执行回调,ajax操作回调,图片加载完成执行回调,AJAX等等。
DOM事件及Node.js事件基于回调机制(Node.js回调可能会出现多层回调嵌套的问题)。

setTimeout的延迟时间为0,这个hack经常被用到,settimeout调用的函数其实就是一个callback的体现

链式调用:链式调用的时候,在赋值器(setter)方法中(或者本身没有返回值的方法中)很容易实现链式调用,而取值器(getter)相对来说不好实现链式调用,因为你需要取值器返回你需要的数据而不是this指针,如果要实现链式方法,可以用回调函数来实现setTimeout、setInterval的函数调用得到其返回值。由于两个函数都是异步的,即:他们的调用时序和程序的主流程是相对独立的,所以没有办法在主体里面等待它们的返回值,它们被打开的时候程序也不会停下来等待,否则也就失去了setTimeout及setInterval的意义了,所以用return已经没有意义,只能使用callback。callback的意义在于将timer执行的结果通知给代理函数进行及时处理。

回调函数的传递

上面说了,要将函数引用或者函数表达式作为参数传递。

$.get('myhtmlpage.html', myCallBack);//这是对的
$.get('myhtmlpage.html', myCallBack('foo', 'bar'));//这是错的,那么要带参数呢?
$.get('myhtmlpage.html', function(){//带参数的使用函数表达式
myCallBack('foo', 'bar');
});

另外,最好保证回调存在且必须是函数引用或者函数表达式:
(callback && typeof(callback) === "function") && callback();

回调函数的使用示例

例子1

如果不用回调,在alert弹出框之后,我们还没有点击确认的时候,就刷新了,不合常规。

What is a callback function in jquery

例子2

如果不用回调,ajax与弹出框函数分开写,结果就会是在弹出框之后,我们还没进行点击选择,就已经发送ajax了,然后再弹出弹出框,不符合我们的需求,所以不能这样。

function ops(act,uid) {
        callback = {
          "ok":function(){
              $.ajax({
                  url:common_ops.buildWebUrl("/account/ops"),
                  type:'POST',
                  data:{
                      act:act,
                      uid:uid,
                  },
                  dataType:'json',
                  success:function(res){
                      allback = null;
                      if(res.code == 200) {
                          callback =function () {
                              window.location.reload();
                          }
                      }
                      common_ops.alert(res.msg,callback);
                  }
              });
          },
          "cancel":function(){
 
          }
};
        //记住callback是一个回调函数
        //回调函数是作为一个参数在函数中
        //然后在函数内部让他运行
common_ops.confirm((act == "remove")?"确定删除吗?":"确定恢复吗?",callback);
 
 
 
    //四个参数
    //第一个是信息
    //第二个是按钮
    //第三个是成功的方法
    //第四个是失败的方法
    confirm:function( msg,callback ){
        callback = ( callback != undefined )?callback: { 'ok':null, 'cancel':null };
        layer.confirm( msg , {
            btn: ['确定','取消']
        }, function( index ){
            if( typeof callback.ok == "function" ){
                callback.ok();
                layer.close( index );
            }
        }, function( index ){
            if( typeof callback.cancel == "function" ){
                callback.cancel();
                layer.close( index );
            }
        });
    },

例子3

<!DOCTYPE html>
<html>
	<head>
 
	</head>
<body>
	<div>
		<button>按钮</button>
	</div>
</body>
</html>
 
<script ></script>
<!-- 不用回调的 -->
<!-- <script type="text/javascript">
	var object = {
		init:function(){
			this.eventbind();
		},
		eventbind:function(){
			$("button").click(function(){
				alert("111");
			})
			// 不用回调这边都看不到弹出框,更不要说点击确定了
			window.location.reload();
		}
	}
	$(document).ready(function(){
		object.init();
	})
</script> -->
 
<!-- 用回调的 -->
<script type="text/javascript">
 
	var back = "回调函数"
 
	function callback(){
			alert(back);
			window.location.reload();
	}
 
	var object = {
	
		main:"主函数",
 
		tanchu:function(msg,callback){
			alert(object.main);
 
			if (typeof callback == "function"){
				callback();
			}
		},
	}
 
	$(document).ready(function(){
		$("button").click(function(){
			object.tanchu("信息",callback);
		})
	})
</script>

代码4代码优化

<!DOCTYPE html>
<html>
	<head>
	<meta charset="utf-8">
	</head>
<body>
	<div>
		<button id="noback">按钮</button>
		<hr>
		<button id="hasbac">按钮</button>
	</div>
</body>
</html>
 
<script src="./jquery-3.6.1.min.js"></script>
<!-- 不用回调的 -->
<!-- <script type="text/javascript">
	var obje = {
		init:function(){
			this.eventbind();
		},
		eventbind:function(){
			$("#noback").click(function(){
				alert("1");
			})
			// 还没出现111呢  已经弹出1了
	        alert("2 没有弹出1 应该先弹出1的");
		}
	}
	$(document).ready(function(){
		obje.init();
	})
</script> -->
 
<!-- 用回调的 -->
<script type="text/javascript">
 
	var hasbac = {
		main:"主函数",
		back:"回调函数",
		init:function(){
			this.eventbind();
		},
 
		eventbind:function(){
			
			// 把callback让入了tanchu方法中,就会顺序执行了
			// 如果直接写会导致直接弹出
			$("#hasbac").click(function(){
				hasbac.tanchu("点击",hasbac.callback);
			})
			// alert(hasbac.back);
			// window.location.reload();
		},
 
		// 以下两个就是回调函数的写法
		tanchu:function(msg,func){
			alert(msg);
 			alert(hasbac.main);
 
			if (typeof hasbac.callback == "function"){
				hasbac.callback();
			}
		},
 
		callback:function(){
			alert(hasbac.back);
			window.location.reload();
		},
	}
	$(document).ready(function(){
		hasbac.init();
	})
</script>

总结总述

函数作为参数输入到函数中,在主函数中进行顺序执行,就是回调函数。

【推荐学习:jQuery视频教程web前端视频

The above is the detailed content of What is a callback function in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!