回调函数:
1、什么是回调函数?
回调函数又称为回调,将a函数作为参数传入b函数中,b函数在执行过程中根据时机或条件来决定是否调用a函数,a函数就是回调函数。
2、实现机制
- 定义一个回调函数(普通函数)
- 将回调函数的函数引用地址作为参数传递给调用者(调用者本身也是一个函数)
- 当特定的条件或时机发生的时候,调用者使用函数指针调用回调函数对事件进行处理
function show(){
console.log("今天天好黑哦");
}
setInerval(show,1000);
回调函数的用途:
事件注册,异步函数
通常用于达到某个时机或条件时需要执行代码的情况,我们就会使用回调函数,
回调函数案例
[
{"name":"小芳","age":17},
{"name":"小❀","age":27},
{"name":"小霞","age":18},
{"name":"小王","age":10}
]
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>回调函数</title>
<script src="./jquery-3.4.1.min.js"></script>
</head>
<body>
<script>
;(function(){
$.fn.show=function (url,fn){
var iframe=$('<iframe src="'+url+'"></iframe>').appendTo('body');
console.log('1111')
iframe.on('load',function(){
data=$(this.contentDocument).find('body').text();
data=JSON.parse(data);
fn(data);
console.log("2222")
});
}
})();
//调用插件获取数据
$('body').show('./07.json',function(a){
console.log(a);
})
</script>
</body>
</html>