一个函数作为参数传递给另一个函数,这个函数就是回调函数。
例如:
//函数声明
function A(){ …… }
function B( callback ){ callback && callback(); }
//函数调用
B(A); //函数A即为函数B的回调函数
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box {
width: 200px;
height: 200px;
background: red;
border: 1px solid #000;
font-size: 50px;
}
.modal {
width: 100%;
height: 100%;
position: fixed;
left: 0;
top: 0;
z-index: 10;
background: rgba(0, 0, 0, .5);
}
.confirmBox {
width: 300px;
height: 200px;
border: 1px solid #ccc;
background: #fff;
text-align: center;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 20;
padding: 10px;
}
button {
width: 100px;
height: 30px;
}
</style>
<script>
window.onload = function () {
function confirmBox(txt, callback) {
//创建模态层
var modal = document.createElement('div');
modal.className = 'modal';
//创建弹框
var conf_box = document.createElement('div');
conf_box.className = 'confirmBox';
conf_box.innerHTML = '<p>' + txt + '</p><br><br><br><br><button type="button">确定</button>'+
'<button type="button">取消</button>';
var aBtn = conf_box.getElementsByTagName('button');
aBtn[0].onclick = function () {
document.body.removeChild(conf_box);
document.body.removeChild(modal);
callback && callback();
};
aBtn[1].onclick = function () {
document.body.removeChild(conf_box);
document.body.removeChild(modal);
};
//添加到页面中
document.body.appendChild(modal);
document.body.appendChild(conf_box);
}
//======================================================================
var oBox = document.getElementById('box');
oBox.onclick = function () {
//这里进行回调,实现具体需求
confirmBox('你确定要删除吗?', function () {
document.body.removeChild(oBox);
});
};
};
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
其它参考:http://www.cnblogs.com/lishuxue/p/5999682.html
本文纯属学习交流,部分内容来源于网络,如有侵犯请及时与本人联系。
火星时代教育 Helen