简体   繁体   中英

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

I've created a method that automatically populates the view with the Carrierwave image that is being uploaded. But, the broken image box shows by default when I use it. I've added a JS function that removes the broken image box upon detection. The only problem is that the image doesn't repopulate the view after the method is called. I'll post the JS code below.

post.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();
      });
    });
  });
});

Use this variable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM