【问题标题】:rails nested form jquery image previewrails嵌套表单jquery图像预览
【发布时间】:2015-06-25 06:08:34
【问题描述】:

我正在使用带有 jquery 嵌套形式的 rails。如何在自己的图像标签中预览我要上传的图像。在上图中。每次我添加新图片时,都会在第一个图片标签上进行审核。

这是我的 html 代码:

<%= f.fields_for :product_images do |builder| %>

  <div class="row">
    <div class="col-xs-6">

      <div class="form-group">
        <%= f.label 'Upload Image' %>
        <%= builder.file_field :image, class: 'form-control', onchange: 'readURL(this);' %>
        <small class="pull-right">
          <%= builder.link_to_remove "Remove this image" %>
        </small>
      </div>

    </div>

    <div class="col-xs-6">
      <div class="form-group">
        <%= f.label 'Image: ' %> <br>
        <%= image_tag builder.object.image_url(:small), id: 'img_prev' if builder.object.image_url.present? %>
      </div>
    </div>
  </div>

  <% end %>

  <div class="form-group">
    <%= f.link_to_add "Add image", :product_images, class: 'btn btn-success' %>
  </div>

<% end %>

和我的 jquery 脚本:

// image preview
function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        $('#img_prev')
          .attr('src', e.target.result)
          // .width(150);
          .height(100);
      };

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

【问题讨论】:

    标签: javascript jquery html ruby-on-rails


    【解决方案1】:

    jQuery:

    // Set image preview on selection
    function readURL(input, div_id) {
      div_id = "#" + div_id;
      if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $(div_id).attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
      }
    }
    

    导轨:

    <%= f.fields_for :pictures do |pic| %>
        <%= pic.file_field :picture, :onChange => "readURL(this, #{pic.index})" %>
        <img id="<%= pic.index %>" src="<%= image_url 'image-placeholder.png' %>">
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多