JavaScript-回调函数

本文通过一个具体的HTML示例,展示了如何使用JavaScript中的回调函数来实现弹窗确认后删除元素的功能,深入浅出地介绍了回调函数的基本概念及应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个函数作为参数传递给另一个函数,这个函数就是回调函数。

例如:

//函数声明  
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值