You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery表格行编辑时实验室报告文件区域重复显示问题求助

jQuery表格行编辑时实验室报告文件区域重复显示问题求助

Hey Chinni,我仔细看了你的问题描述和代码,发现几个关键问题导致了文件区域重复显示的情况,咱们一步步来排查和解决:

问题根源分析

  1. 全局变量labReportUrls的干扰:你用了全局的labReportUrls存储上传的文件URL,这会导致不同行的编辑操作互相污染——比如编辑行A上传的文件URL,会被带到行B的编辑操作中,最终导致重复显示。
  2. Ajax回调中this指向错误:在文件上传的Ajax success回调里,$(this)不再指向触发上传的文件输入框,而是指向Ajax的配置对象,这会导致你错误地获取rowId,甚至可能意外更新多个行的文件区域。
  3. 临时URL未按行隔离:每次进入编辑模式时,没有清空当前行的临时上传URL,导致旧的临时URL被重复追加到现有文件列表中。

具体修复步骤

1. 替换全局labReportUrls为按行存储的对象

把全局的labReportUrls改成一个按rowId存储的对象,确保每行的临时上传URL互相独立:

// 初始化:代替原来的全局labReportUrls
let rowLabReportUrls = {};

2. 进入编辑模式时清空当前行的临时URL

在点击"Edit"进入编辑状态时,清空当前行的临时上传URL,避免残留旧数据:

else {
    $(this).text('Update');
    $row.find('input, select').prop('disabled', false);

    const $labReportContainer = $row.find('.labReport');
    $labReportContainer.empty();

    // 关键:清空当前行的临时上传URL
    rowLabReportUrls[rowId] = [];

    // 添加文件输入框(仅一次)
    $labReportContainer.append(`
        <input type="file" class="form-control labReportInput" accept="application/pdf">
    `);

    // 追加现有文件
    if (existingLabReports[rowId] && existingLabReports[rowId].length > 0) {
        const existingReportsHtml = existingLabReports[rowId].map(link => `
            <div class="existing-lab-report" data-url="${link.trim()}">
                <a href="${link.trim()}" target="_blank">${link.substring(link.lastIndexOf('/') + 1)}</a>
                <i type="button" class="remove-lab-report-btn fa fa-times" style="font-size: 14px; color: #dc3545;"></i>
            </div>
        `).join('');
        $labReportContainer.append(existingReportsHtml);
    }
}

3. 修复Ajax回调中的this指向问题

在文件上传的change事件中,提前保存当前的输入框和行对象,避免Ajax回调中this指向错误:

$('#addPackagingModuleList tbody').on('change', '.labReportInput', function () {
    // 提前保存当前输入框和行的jQuery对象
    const $input = $(this);
    const $row = $input.closest('tr');
    const rowId = $row.find('.edit-btn').data('id');
    const labReportFiles = this.files;

    Array.from(labReportFiles).forEach(file => {
        if (file.size > MAX_FILE_SIZE) {
            alert('File size exceeds the 1MB limit.');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        $.ajax({
            url: '/admin/sys/sec/qr/uploadFile',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function (response) {
                if (response.status) {
                    // 将新上传的URL存入当前行的临时数组
                    rowLabReportUrls[rowId].push(response.data);

                    // 合并现有文件和临时上传的文件
                    const existingReports = existingLabReports[rowId] || [];
                    const allReports = [...existingReports, ...rowLabReportUrls[rowId]];

                    // 生成文件链接HTML
                    const labReportLinks = allReports.map(link => `
                        <div class="existing-lab-report" data-url="${link.trim()}">
                            <a href="${link.trim()}" target="_blank">${link.substring(link.lastIndexOf('/') + 1)}</a>
                            <button type="button" class="remove-lab-report-btn btn-sm btn-danger ms-1">
                                <i class="fa fa-times"></i>
                            </button>
                        </div>
                    `).join('');

                    // 更新当前行的文件区域(用提前保存的$row)
                    $row.find('.labReport').html(`
                        <input type="file" class="form-control labReportInput" accept="application/pdf">
                        ${labReportLinks}
                    `);

                    // 提示信息
                    $('#alert-message').text(response.message);
                    $('#alert-container').removeClass('alert-danger').addClass('alert-success').show();

                    setTimeout(function () {
                        $('#alert-container').fadeOut();
                    }, 3000);
                } else {
                    alert('Error uploading file.');
                }
            },
            error: function () {
                alert('Error uploading file. Please try again.');
            }
        });
    });
});

4. 更新提交时使用当前行的临时URL

在点击"Update"提交数据时,使用当前行的临时URL数组,提交后清空该数组:

if (isEditing) {
    $(this).text('Edit');
    $row.find('input, select').prop('disabled', true);

    // 获取当前行的临时上传URL
    const tempUrls = rowLabReportUrls[rowId] || [];
    // 合并现有文件和临时上传的文件
    const labReportLink = existingLabReports[rowId].concat(tempUrls).join(',');

    const updatedData = {
        id: rowId,
        labReport: labReportLink,
        farmSlide: "",
        farmCertifications: "",
        farmPackagingVideo: "",
        growerName: $row.find('.grower-name').val(),
        crop: $row.find('.crop').val(),
        variety: variety === 'Other' ? otherVariety : variety,
        farmRegistrationNumber: $row.find('.farm-registration-number').val(),
        ggn: $row.find('.ggn').val(),
        lotTracebility: $row.find('.lot-traceability').val(),
        customerName: $row.find('.customerName').val(),
    };

    $.ajax({
        url: '/admin/sys/sec/edit/qrcode/details',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(updatedData),
        success: function (response) {
            if (response.status) {
                table.ajax.reload();
                $('#alert-message').text(response.data);
                $('#alert-container').show();
                setTimeout(function () {
                    $('#alert-container').fadeOut();
                }, 3000);
                // 清空当前行的临时URL
                delete rowLabReportUrls[rowId];
                location.reload();
            } else {
                alert('Error updating data.');
            }
        },
        error: function () {
            alert('Failed to update data.');
        }
    });
}

额外检查点

  • 确保表格的每一行只有一个带有.labReport类的容器,避免$row.find('.labReport')找到多个元素导致重复添加。
  • 检查existingLabReports的初始化逻辑,确保每次表格刷新后,该数组里的文件URL是唯一的,没有重复项。

这样修改后,应该就能解决点击编辑按钮后文件区域重复显示的问题啦!

备注:内容来源于stack exchange,提问作者Chinni Ch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 14:19:33