Cocoon gem,图片上传预览

时间:2015-04-03 08:19:02

标签: jquery ruby-on-rails carrierwave cocoon-gem

我的嵌套表格部分:

<div class="row nested-fields">
  <div class="col-lg-8 field">
    <div class="gallery-images">
      <% if f.object.picture.present? %>
        <%= image_tag f.object.picture_url, :class=> "gallery-preview-image" %>
      <% else %>
        <img class="gallery-preview-image" src="" alt="your uploaded image" />
      <% end %>
    </div>
    <div class="clearfix"></div>
    <div class="gallery-image-text">
      <%= f.label :text %><br />
      <%= f.text_field :text %>
      <%= f.hidden_field :gallery_id, :value => @gallery.id %>
    </div>
  </div>
  <div class="col-lg-4 field">
    <p>
      <%= f.label :position %><br />
      <%= f.text_field :position %>
      <%= f.file_field :picture, :id => "upload-gallery-picture", :style => "display: none;" %>
      <%= f.hidden_field :picture_cache, :value => f.object.picture_cache %>
      <%= link_to t('seller_home.gallery.upload_picture').html_safe, "javascript:;", :id => "upload-gallery-picture-link", :onclick => "browseFiles(this);" %>
    </p>
  </div>
  <div class="remove-gallery-image-link">
    <%= link_to_remove_association t('seller_home.gallery.remove').html_safe, f  %>
  </div>
</div>

此外,为了上传图像和显示图像预览,我使用了以下脚本:

<script>

    function browseFiles(){
        $("#upload-gallery-picture").trigger("click");
        changeOfFile();
    }

    function changeOfFile(){
        $("#upload-gallery-picture").change(function(){
            thumbImage(this, $(this).parents('.nested-fields').find('.gallery-images').find('.gallery-preview-image'));
        });
    }

    function thumbImage(input, selecttor) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $(selecttor).attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }


</script>

现在,您可以在每次上传图像时在脚本中看到脚本文件读取器读取文件并在gallery-preview-image中显示其预览。 问题是,每次都有部分负荷。因此,对于每个嵌套字段,都有相同的gallery-preview-image ID。因此,如果我将任何图像上传到任何表单,它将显示顶部表单的预览。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您应该使用类而不是id。一个id在页面上应该是唯一的。一堂课可以重复。

所以写

<%= f.file_field :picture, :class => "upload-gallery-picture", :style => "display: none;" %>

相应地调整你的javascript,所以 请改用$(".upload-gallery-picture")