Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Rails:文件嵌套字段,显示每个字段上所选文件的名称_Javascript_Jquery_Ruby On Rails_Cocoon Gem - Fatal编程技术网

Javascript Rails:文件嵌套字段,显示每个字段上所选文件的名称

Javascript Rails:文件嵌套字段,显示每个字段上所选文件的名称,javascript,jquery,ruby-on-rails,cocoon-gem,Javascript,Jquery,Ruby On Rails,Cocoon Gem,我使用cocoon gem添加带有嵌套字段的图像: <div id="attachments"> <%= f.simple_fields_for :attachments do |attachment| %> <%= render 'products/attachment_fields', form: attachment %> <% end %> <div class="links" id="add

我使用
cocoon gem
添加带有嵌套字段的图像:

<div id="attachments">
    <%= f.simple_fields_for :attachments do |attachment| %>
    <%= render 'products/attachment_fields', form: attachment  %>
    <% end %>
        <div class="links" id="add_attachment" style="display: inline; float: right;">
           <%= link_to_add_association 'add more images', f, :attachments, form_name: 'form' %>
         </div>
</div>

所以现在我有点被困在如何实现上述功能上。非常感谢您的帮助。

html id在页面上应该是唯一的,因此您不能对重复字段使用唯一id。虽然页面可以正确呈现,但在发布表单时,它将忽略重复的id(从而发布不正确/不完整的信息)

其次,使用jquery很容易找到最近的元素

因此,在嵌套字段的部分中,删除所有id,然后编写如下内容

<%= form.input :images, label: false, as: :file, 
      :input_html => { :class => 'custom-file-input', :style=>"cursor: pointer"} %>
<label class="custom-file-label" style="cursor: pointer;">Choose file</label>
有几个选项,我不确定哪个选择器工作得最好。您可以向上移动,然后选择正确的标签:

 $(this).closest('.nested-fields').find('label.custom-file-label') 
我不确定仅仅寻找最近的
标签是否有效

 $(this).closest('label.custom-file-label') 
或者像我上面所做的那样,使用正确的选择器查找同级

$(".nested-fields .custom-file-input").change(function(){
  $(this).siblings("label.custom-file-label").text(this.files[0].name);
});
 $(this).closest('.nested-fields').find('label.custom-file-label') 
 $(this).closest('label.custom-file-label')