【发布时间】:2021-03-19 05:05:53
【问题描述】:
我在rails中开发我的应用程序,在我的应用程序中,我通过ajax在模态窗口中提取表单,表单有一个茧按钮来添加嵌套记录,当使用茧添加新的嵌套资源时出现问题那些新字段不响应检测字段是否更改值的 javascript 函数
我的应用程序.js
function validateFileType(){
$( ".file_to_upload" ).change(function() {
alert( "Handler for .change() called." );
});
}
我的 index.haml.erb 的一部分:
=link_to '<i class="fa fa-picture-o"></i>'.html_safe, adjuntar_archivos_path(:id => record), :remote => true
#adjuntar_archivos
我在控制器中的方法
def adjuntar_archivos
@billing = Billing.find_by_id(:id)
end
我的 adjuntar_archivos.js.erb
$("#adjuntar_archivos").html("<%=j render :partial => 'adjuntar_archivos'%>");
$("#addDataModelModal").modal("show");
validateFileType();
我的部分 _adjuntar_archivos.html.haml
#addDataModelModal.modal.fade{"aria-hidden" => "true", "aria-labelledby" => "exampleModalLabel", role: "dialog", tabindex: "-1"}
.modal-lg.modal-dialog{role: "document"}
.modal-content
= form_for(@billing, remote: true) do |f|
.modal-header
%h5#addDataModelModalLabel.modal-title Archivos adjuntos
%button.close{"aria-label" => "Close", "data-dismiss" => "modal", type: "button"}
%span{"aria-hidden" => "true"} ×
.modal-body
.links
= link_to_add_association "<i class='fa fa-plus'></i> Añadir adjunto".html_safe, f, :billing_files, partial: 'billing_file_fields',:"data-association-insertion-node" => "tbody.adjuntos",:"data-association-insertion-method" => "prepend", class:"btn btn-success btn_naranja btn", id: "link_1"
.row
.col-md-12
#payment_details
%table.tabla_personalizada#tabla_detalle_pago
%thead
%tr
%th Descripción
%tbody.adjuntos
= f.fields_for :billing_files do |billing_file|
= render 'billing_file_fields', f: billing_file
.modal-footer
%button.btn.btn-secondary{"data-dismiss" => "modal", type: "button"} Close
.text-center
= f.submit 'Guardar', :class => 'pull-right btn btn-primary'
我的部分 _billing_file_fields.html.haml
%tr.nested-fields.detalle_pago
%td= f.text_field :description, class: 'form-control file_to_upload'
如何让 cocoon 创建的新字段也运行我的 javascript 函数的 .change 方法?
更新:
我尝试通过以下方式在部分“billing_file_fields.html.haml”中执行该函数:
%tr.nested-fields.detalle_pago
%td= f.text_field :description, class: 'form-control file_to_upload'
- content_for :javascript do
:javascript
validateFileType();
但还是不行
【问题讨论】:
-
您必须重新运行 Javascript 才能使 .change 方法起作用。当您加载页面时,您会加载初始 Javascript,当您动态添加新记录时,页面无法识别它,因为它不是初始加载的一部分。您可以尝试将
validateFileType();放入_billing_file_fields.html.haml -
@VictorLuna 我试过了,但是在渲染部分时没有执行 javascript 代码。我用我使用的代码更新了帖子
标签: javascript ruby-on-rails ruby-on-rails-4 ruby-on-rails-5 cocoon-gem