我有一个部分显示模态,当模态弹出时,所有模态内容都是动态生成的。我创建的javascript文件中的click事件不会在click上触发,我认为这是因为元素是动态创建的。一旦模态打开,如何才能加载javascript文件?我试图在按钮上添加一个加载图标,一旦AJAX响应返回(在create.js中执行),该按钮将被关闭。码:
部分:
#list_item_product_modal.modal._large.fade
.modal-dialog
.modal-content
.modal-body
.product_picker.product_picker_always_open
.row
.col-xs-12.col-md-10.col-md-offset-1
%h4.text-center.picker_title{ style: 'z-index:99;' }
%span
Add a Product
.input-group.input-group-lg
= text_field_tag :suggestion_search, '', class: 'form-control product_picker_input modal-focus', autocomplete: 'off', placeholder: 'Start typing a product name...'
%span.input-group-btn
%button.product_picker_submit.btn.btn-default
%i.fa.fa-search
.hidden-xs.hidden-sm.col-md-1.text-right
%button.close{ type: :button, 'data-dismiss' => 'modal', 'aria-hidden' => 'true' }
×
-# = form_tag main_app.products_path(), method: :post do
= form_tag main_app.list_items_path, data: { passthru: current_user.nil?, remote: true } do |f|
= hidden_field_tag :success, 'back'
= hidden_field_tag :list_id, args[:list].try(:id) || '0'
.product_picker_inner
.product_picker_body
.product_picker_details
.product_picker_details_default
= hidden_field_tag :product_id, '{raw-product_id}'
= hidden_field_tag :added_from, 'search'
%h4.text-center
{escaped-title}
.text-center.product_picker_category
%span
{escaped-category}
.product_picker_content
.row
.col-xs-12.col-md-6.product_picker_avatar6
%img.img.img-responsive.center-block{ src: '#{raw-avatar}' }
-# .rectangle-avatar.contain-image{ style: 'background-image: url("{encoded-avatar}")' }
.col-xs-12.col-md-6.product_picker_description
{escaped-description}
.col-xs-12.col-md-6
.text-center{ style: 'margin:1em 2em 0.3em 0' }
price:
%b
{raw-price_formatted}
.row{ style: 'padding: 1em 0 0 0;' }
.col-xs-12
.fancy-span{ style: 'font-size: 0.8em' }
%span Tell us about this product
= text_area_tag :comment, '', class: 'form-control'
.text-center.product_picker_controlls
= button_tag 'ADD', type: 'submit', class: 'btn btn-primary btn-lg t03e', id: 'product-{raw-product_id}'
-# %a.btn.btn-primary.btn-lg.t03e{ href: "#{products_path( list_id: args[:list].try(:id) || '0', success: 'back' )}&u={raw-id}", data: { method: :post } }
ADD
.product_picker_loading_overlay
%div{ style: 'position: absolute;top: 50%;left: 0;line-height: 1.1em;right: 0;text-align: center;font-size: 40px;margin: -20px 0 0 0;' }
%i.fa.fa-circle-o-notch.fa-spin
.text-center{ style: '' }
%a{ href: '#', 'data-dismiss' => 'modal' }
CLOSE
JS:
$(document).ready(function(){
$('.btn.btn-primary.btn-lg.t03e').click(function(){
$( this ).html('<i class="fa fa-circle-o-notch fa-spin"></i>');
});
});
最佳答案
如您所说,添加的侦听器用于文档中已经存在的元素。
并且,下面的代码是为将来将要创建的元素(通常在body
元素内部创建)添加侦听器的方法:
$(document).ready(function(){
$('body').on('click', '.btn.btn-primary.btn-lg.t03e', function(){
$( this ).html('<i class="fa fa-circle-o-notch fa-spin"></i>');
});
});