是否可以在js.erb文件中呈现javascript文件?我在new.js.haml文件中呈现了一个模式。但是,我有一些javascript代码仅在调用该模式时才需要运行。
new.js.haml
$('.modal-content').html("#{ j(render partial: 'new') }");
当new.js.haml被称为upload.js时,我希望能够调用此文件或呈现此文件
$ ->
files = [];
$("#upload_button").click ->
$("#file_input").trigger "click";
$("#file_input").change (event) ->
file = event.target.files[0];
files.push(file);
uploadfile files.length - 1, file;
uploadfile = (index, file) ->
formData = new FormData();
formData.append "file", file;
fileitem = "
<li class='file-item success'>
<div class='active'>
<span class='remove'>×</span>
<span>#{file.name}</span>
</div>
<div class='lds-ellipsis'><div></div><div></div><div></div><div></div></div>
</li>
";
$('#filelist').append fileitem;
setRemove();
setRemove = ->
$(".remove").unbind();
$(".remove").click ->
index = $(@).parent().parent().index();
files.splice index, 1;
$('.file-item').eq(index).remove();
这是我的表单文件,已呈现,但由于已经加载在主页上而没有调用upload.js文件。单击新表单按钮后,它将以模式显示此表单。
- @ticket.errors.full_messages.each do |message|
.error= message
= render 'layouts/standard_flash'
%ZenTicketForm{ title: 'Submit Help Request', :multipart => true, data: { remote: true } }
.col-xs-12.col-sm-12.col-md-12.col-lg-12{style: 'padding:0;'}
.col-xs-12.col-sm-12.col-md-12.col-lg-6
%dl.dl-horizontal
%dt Type
%dd.show-more-container
%ZenSelect#ticket_type{options: ['Questions', 'Incidents', 'Problems', 'Tasks'],
class: 'select2',
placeholder: t('activerecord.placeholders.zen_support/ticket.ticket_type') }
.col-xs-12.col-sm-12.col-md-12.col-lg-12
%dl.dl-horizontal
%dt Subject
%dd.show-more-container
%input.form-control{ type: 'text',
name: 'zen_support_ticket[subject]',
placeholder: t('activerecord.placeholders.zen_support/ticket.subject') }
.col-xs-12.col-sm-12.col-md-12.col-lg-6
%dl.dl-horizontal
%dt Priority
%dd.show-more-container
%ZenSelect#priority{ options: ['Low', 'Normal', 'High', 'Urgent'],
data: { placeholder: "activerecord.placeholders.zen_support/ticket.priority" },
class: 'select2' }
.col-xs-12.col-sm-12.col-md-12.col-lg-12
%dl.dl-horizontal
%dt Comment
%dd.show-more-container
%ZenTextArea#comment{ placeholder: t('activerecord.placeholders.zen_support/ticket.comment'),
error: @zendesk_ticket.errors&.dig(:comment) }
%dl.dl-horizontal
.new-show-less
%button.fileUpload.btn.btn-default#upload_button{type: "button"}
Attach File
%input.upload#file_input{:name => "attachments[]", multiple: true, :type => "file"}
%ul#filelist
答案 0 :(得分:0)
您可以将JS代码直接放在js.erb文件中,并且仅在呈现该部分时才执行。
查看更多: https://guides.rubyonrails.org/working_with_javascript_in_rails.html