使用JS删除损坏的图像框无法正常工作.导轨 4.

Removing Broken Image Box with JS not working correctly. Rails 4

本文关键字:常工作 工作 导轨 损坏 删除 JS 图像 使用      更新时间:2023-09-26

我创建了一个方法,该方法会自动使用正在上传的Carrierwave图像填充视图。但是,当我使用它时,默认情况下会显示损坏的图像框。我添加了一个JS函数,可以在检测到时删除损坏的图像框。唯一的问题是,调用该方法后,图像不会重新填充视图。我将在下面发布JS代码。

帖子.js

$(document).ready(function () {
  $(function () {
    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
          $('#img_prev').attr('src', e.target.result);
        };
        reader.readAsDataURL(input.files[0]);
      }
    }

    //Add uploaded image to placeholder.
    $("#img-upload").change(function () {
      $('#img_prev').removeClass('hidden');
      readURL(this);
      //Remove Broken Image
      $('img').error(function () {
        $('img[src="' + $(this).attr('src') + '"]').remove();
      });
    });
  });
});

使用this变量。

$('img').error(function () {
    $(this).remove();
});