js动态绑定数据的闭包问题

本文介绍了解决文件上传时循环绑定数据仅显示第一个数据的问题。通过定义全局变量和使用button点击事件接收数据,结合input的onchange事件触发函数,实现了在后台循环中动态显示siteId和examinationRoomId,确保每次上传都能正确绑定对应的数据。

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

以文件上传举例,循环绑定数据时只显示第一个固定数据

解决方案:

后台循环得到siteId和examinationRoomId数值,按钮采用拼接方法显示在页面上

e.setUploadCheckinRecord("<input type='file' id='btn_file' style='display:none' onchange = 'ExaminationRecords.aa()'>"+
"<button class='btn btn-primary' onclick=ExaminationRecords.uploadCheckinRecord(" +siteId+ ","+examinationRoomId+")>上传考场照片</button>");

js函数

使用button的点击事件接收数据并定义为全局变量,input框使用onchange事件触发函数

ExaminationRecords.aa=function(){
    var obj =document.getElementById("btn_file");
    var len = obj.files.length;
    var fileName;
    for (var i = 0; i < len; i++) {
        fileName = obj.files[i].name;
    }
    var con=confirm("确定上传"+fileName+"吗?");
    if(con==true){
         var formData = new FormData();
        formData.append('file',$('#btn_file')[0].files[0]);
        formData.append('siteId',sId);
        formData.append('examinationRoomId',eId);
        console.log(eId);
        $.ajax({
            url:'/examinationRecords/uploadCheckinRecord',
            type:'post',
            processData:false,
            contentType:false,
            data:formData,
            success:function (data) {
                Feng.success("上传成功!");
                ExaminationRecords.table.refresh();
            },
            error:function(data){
                Feng.error("上传失败!" + data.responseJSON.message + "!");
            }
        })
    }
};

ExaminationRecords.uploadCheckinRecord=function(siteId,examinationRoomId){
    document.getElementById("btn_file").click();
    sId = siteId;
    eId = examinationRoomId;
};

完美解决,请自动忽略那该死的aa函数名,哈哈

解决思路:定义全局变量进行抛出

转载于:https://www.cnblogs.com/xiaowangxiao/p/11550283.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值