有些产品有很多图片。在产品编辑模板上,有一部分用于添加和删除图像
_edit_images.html.erb 的
<% if @product.images != nil && @product.images.count > 0 %>
<ul id="images_index" data-update-url="<%= sort_images_url %>">
<% @product.images.order( :position ).each do |i| %>
<%= content_tag_for :li, i do %>
<%= image_tag i.image.url( :thumb ), class: "img-polaroid" %>
<%= link_to image_tag('icons/remove.png'), remove_image_from_product_products_path( product_id: @product.id, image_id: i.id ), remote: true, method: :get, data: { confirm: "Sure?"}, class: 'delete_item' %>
<% end %>
<% end %>
</ul>
<% end %>
<a class="btn btn-default" id='add_image' href="#add_image_form"><span class="glyphicon glyphicon-plus"></span></a>
<%= form_tag '/admin/images', remote: true, multipart: true, id: 'add_image_form' do %>
<input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>" />
<input type="hidden" name="product_id" value="<%= @product.id %>" />
<br><%= label_tag 'name', 'Image title' %>
<%= text_field_tag 'title', '', id: "add_image_title", class:'form-control' %><br>
<%= label_tag 'name', 'Выберите файл' %>
<%= file_field_tag 'file', class:'form-control'%><br><br>
<button type="submit" class="btn btn-primary">Add image</button>
<% end %>
表单调用Images控制器创建操作
def create
image = Image.create( title: params[ :title ], image: params[ :file ] )
@product = Product.find_by id: params[ :product_id ]
@product.images << image
respond_to do |format|
format.html { redirect_to admin_products_path }
format.js { render '/products/edit_images' }
end
end
添加图片并发出后,javascript无效。任何人都可以建议在渲染部分后重新加载javascript的方法吗?
更新 images.js.coffee
jQuery ->
$("a#add_image").on "click", (e) ->
$("form#add_image_form").toggle()
e.preventDefault()
$('div.actions ul#images_index').sortable
axis: 'y'
update: ->
$.post($(this).data('update-url'), $(this).sortable('serialize'))
答案 0 :(得分:0)
答案很简单。在页面更新上设置事件侦听器可以解决问题
images_update = ->
$("#add_page_image").on "click", (e) ->
$("form#add_image_form").toggle()
e.preventDefault()
$('#page_images_index').sortable
axis: 'y'
update: ->
$.post($(this).data('update-url'), $(this).sortable('serialize'))
$(document).on 'page:update', ->
images_update()