Definition and usage example of jQuery callback function

  • 2020-05-09 18:04:54
  • OfStack

This article illustrates the definition and usage of the jQuery callback function. Share with you for your reference. The specific analysis is as follows:

The callback function is widely used in jQuery code, so it is necessary to have a precise understanding of it. The following is a simple introduction to this method through an example.

The code example is as follows:

With the callback function, a prompt box will pop up when div is completely hidden.


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<style type="text/css">
div{
  height:150px;
  width:150px;
  background-color:green;
  margin-top:10px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("div").slideUp(2000,function(){alert(" Is hidden ")});
  })
})
</script>
</head>
<body>
<div></div>
<button> Click to view </button>
</body>
</html>

The above code runs very well and in good order. In many real-world applications, you want your code to complete one action and then do another.
The code should look exactly like the above code, but the result is not what we expected. Instead, the div element is hidden after the prompt box appears. This is not to say that slideUp() has not been started.


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<style type="text/css">
div{
  height:150px;
  width:150px;
  background-color:green;
  margin-top:10px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("div").slideUp(2000);
    alert(" Is hidden ");
  })
})
</script>
</head>
<body>
<div></div>
<button> Click to view </button>
</body>
</html>

The following is a simple and popular summary of what a callback function is. Look at this code:


function a(){alert(" I am a 1 A function ")}
a();

The above is the most common way to call a function, with the implementation of the function to call directly, but the callback function is not such, it is to pass its address as a parameter to another function, when a particular event will be used as a parameter passed over the callback function address to call the callback function. In the case of the code above that USES the callback function, it passes the address of the function function to the slideUp() method, and when the slideUp() action is complete, the function function is called using the passed address parameter.

I hope this article has helped you with your jquery programming.


Related articles: