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

如何将CropperJS裁剪结果赋值到对应新增行的隐藏输入框

问题分析与解决方案

问题根源:

  • 裁剪完成后硬编码写入固定ID的#baseimg,但新增行的隐藏框ID是baseimg2、baseimg3这类动态生成的ID,无法匹配对应行。
  • 点击图片触发上传时,用document.querySelector('.item-file')只会选中第一个上传框,导致后续行的图片点击也会打开第一个上传框(额外问题,一并修复)。
  • 上传阶段未记录当前操作对应的目标隐藏框,导致裁剪后找不到对应行的输入框。

修复步骤:

  1. 替换图片的点击事件
    把新增行里的onclick="document.querySelector('.item-file').click()"改成onclick="$(this).siblings('.item-file').click()",确保点击当前行的图片只触发本行的上传框。

  2. 在上传时记录目标隐藏框
    在$('.item-file').on('change', function() {事件里,添加代码获取当前上传框所在行的隐藏输入框,存入全局变量:

    // 保存当前上传框对应的隐藏输入框
    currentBaseImg = $(this).siblings('input[name="baseimg"]');
    
  3. 裁剪完成后写入对应隐藏框
    修改$('#cropImageBtn').on('click', function(ev) {里的代码,把固定写入#baseimg的逻辑替换为写入之前记录的目标隐藏框:

    if (currentBaseImg) {
      currentBaseImg.val(resp);
    }
    
  4. 修正取消按钮的清空逻辑
    取消裁剪时,清空当前对应的隐藏框,而非固定的#baseimg:

    if (currentBaseImg) {
      currentBaseImg.val('');
    }
    

修改后的完整代码:

var index = 2;
// 新增全局变量存储当前对应的隐藏输入框
var currentBaseImg;

$("#newstudentbtn").click(function(e) {
  e.preventDefault();
  $(".addstudent").append(`<div class="row mb-3">
          <div class="col-8">
            <input type="text" class="form-control" placeholder="Student name" id="sname">
          </div>
          <div class="col-2 text-center ">
            <img style="width:30px; height:30px;" src="https://cdn-icons-png.flaticon.com/512/83/83574.png" class="item-img" alt="Image" onclick="$(this).siblings('.item-file').click()">
            <input type="file" class="item-file" data-id="hi" name="image" style="display: none;">
            <input id="baseimg${index}" name="baseimg" type="hidden" value="">
          </div>
          <div class="col-2 text-right">
            <button type="button" id="removestudentbtn" class="btn btn-danger">Remove</button>
          </div>
        </div>`);
  index++;
});

var $uploadCrop,
  tempFilename,
  rawImg,
  imageId;
var opts = {
  enableExif: true,
  viewport: {
    width: 300,
    height: 190,
  },
  boundary: {
    width: 350,
    height: 250
  },
  enforceBoundary: true,
  enableZoom: true,
};

function readFile(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('.upload-demo').addClass('ready');
      $('#cropImagePop').modal('show');
      rawImg = e.target.result;
    }
    reader.readAsDataURL(input.files[0]);
  } else {
    swal("Sorry - you're browser doesn't support the FileReader API");
  }
}

$uploadCrop = $('#upload-demo').croppie(opts);
$('#cropImagePop').on('shown.bs.modal', function() {
  $uploadCrop.croppie('bind', {
    url: rawImg
  }).then(function() {});
});

$('.item-file').on('change', function() {
  var file = this.files[0];
  var fileType = file["type"];
  var validImageTypes = ["image/jpg", "image/jpeg", "image/png"];
  if ($.inArray(fileType, validImageTypes) > 0) {
    imageId = $(this).data('id');
    tempFilename = $(this).val();
    $('#cancelCropBtn').data('id', imageId);
    // 保存当前上传框对应的隐藏输入框
    currentBaseImg = $(this).siblings('input[name="baseimg"]');
    readFile(this);
  } else {
    Swal.fire({
      title: 'Error!',
      text: 'Please upload an image file! (png, jpg or jpeg)',
      icon: 'error',
      confirmButtonText: 'OK'
    })
    $(this).val('');
    if (currentBaseImg) {
      currentBaseImg.val('');
    }
    $('#upload-demo').croppie('destroy');
    $uploadCrop = $('#upload-demo').croppie(opts)
  }
});

$('#cancelCropBtn').on('click', function() {
  $('.item-file').val('');
  if (currentBaseImg) {
    currentBaseImg.val('');
  }
  $('#upload-demo').croppie('destroy');
  $uploadCrop = $('#upload-demo').croppie(opts)
});

$('#cropImageBtn').on('click', function(ev) {
  $uploadCrop.croppie('result', {
    type: 'canvas',
    size: 'original',
    quality: 0.4,
    format: 'jpeg',
  }).then(function(resp) {
    $('#cropImagePop').modal('hide');
    // 将结果写入对应的隐藏输入框
    if (currentBaseImg) {
      currentBaseImg.val(resp);
    }
  });
});

内容的提问来源于stack exchange,提问作者Dr.Jamal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:15:57