The callback function refers to a function that is automatically recalled by the caller when the caller finishes processing.
is typically passed through function pointers/references in the Class C language.
jquery also provides a similar mechanism for callback functions. But how to properly pass the callback function is still worth mentioning.
There is a detailed introduction in the guide written by John (JQuery founder).
1. Callbacks with no parameters
$.get (' myhtmlpage.html ', mycallback);
Where Mycallback is the function name. Functions are the basis of JavaScript. Can be passed as a reference variable.
2. Callback with Parameters
Naturally, in the light of previous experience, we would assume that the callback with the parameter would look like this:
$.get (' myhtmlpage.html ', Mycallback (param1, param2));
However, this will not work properly. Mycallback (param1, param2) is executed when the statement is invoked, not later.
The following syntax is correct:
$.get (' myhtmlpage.html ', function () { mycallback (param1, param2);});
This callback function is passed as a function pointer and will be executed after the get operation is completed.
Program Demo:
1 <!DOCTYPE HTML>2 <HTML>3 4 <Head>5 <MetaCharSet= "Utf-8">6 <title>callback function</title>7 <Scriptsrc= "Jquery/jquery-2.1.4.js"type= "Text/javascript"CharSet= "Utf-8"></Script>8 <Scripttype= "Text/javascript">9 $ (document). Ready (function(){Ten $("#btn1"). Click (function(){ One $("#test1"). Text (function(i,origtext) { A return "Old text:"+Origtext+"New Text:hello world! (Index:"+I+")"; - }); - }); the $("#btn2"). Click (function(){ - $("#test2"). HTML (function(i,origtext) { - return "Old HTML:"+Origtext+"new Html:hello <b>world!</b> (index:"+I+")"; - }); + }); - }); + </Script> A </Head> at <Body> - <PID= "Test1">This is<b>Bold body</b>Text.</P> - <PID= "Test2">This is another paragraph<b>Bold body</b>Text.</P> - <ButtonID= "BTN1">Show old/New text</Button> - <ButtonID= "BTN2">Show Old/New HTML</Button> - </Body> in - </HTML>
The callback function in the JavaScript jquery of the Web front end