我正在尝试在Rails中创建一个待办事项列表应用程序,其中包含许多待办事项列表,每个列表都有许多待办事项。当我尝试使用Ajax销毁已完成的待办事项时,我必须在页面消失之前刷新页面。我是Rails和Javascript的新手,所以任何想法都会受到赞赏。
这是我的物品销毁Javascript文件:
<% if @item.destroyed? %>
$('#item-' +<%= @item.id %>).hide();
<% else %>
$('#item-' +<%= @item.id %>).prepend("<div class='alert alert-danger'><%= flash[:error] %></div>");
<% end %>
列表#show视图调用项目partial:
%h1= @title
.row
.col-md-6
= render 'items/item', locals: {items: @items}
.row
.col-md-6
= render 'items/form', locals: {list: @list, item: @item}
= link_to "Edit", edit_list_path(@list), class: 'btn btn-success'
= link_to "Delete List", @list, method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this to-do list?' }
- if @lists.nil?
= link_to "New To-do List", new_list_path, class: 'btn btn-success'
项目部分:
- @items.each do |item|
= item.name
= link_to "", [item.list, item], method: :delete, class: 'glyphicon glyphicon-ok', remote: true
%br/
物品管制员:
class ItemsController < ApplicationController
respond_to :html, :js
def create
@list = List.find(params[:list_id])
@item = @list.items.new(item_params)
@item.user_id = current_user.id
if @item.save
redirect_to @list, notice: 'Your new To-Do Item was saved!'
else
redirect_to @list, notice: 'You forgot to enter a To-Do item. Please try again.'
end
end
def destroy
@list = current_user.lists.find(params[:list_id])
@item = @list.items.find(params[:id])
@title = @list.title
if @item.destroy
flash[:notice] = "\"#{@item.name}\" was deleted successfully."
else
flash[:error] = "There was an error deleting the list."
end
respond_with(@item) do |format|
format.html {render [@list]}
end
end
def item_params
params.require(:item).permit(:name)
end
end
答案 0 :(得分:0)
点击= link_to "", [item.list, item], method: :delete, class: 'glyphicon glyphicon-ok', remote: true
创建的链接后,您的应用会发送删除请求,但不会更改视图。您需要添加一个捕获ajax删除请求成功的事件侦听器,并在视图中隐藏item元素。
这是实现这一目标的粗略代码。我没有测试代码,但我认为你可以得到这个想法。
item partial:
.item-container
- @items.each do |item|
.item
= item.name
= link_to "", [item.list, item], method: :delete, class: 'glyphicon glyphicon-ok', remote: true
JS:
$(document).ready(function() {
$('.item-container').on('ajax:success', function() {
$(this).closest('.item').hide();
});
};
参考文献:
顺便说一句,你在哪里放置你发布的JavaScript代码?我怀疑它是否会被执行。
答案 1 :(得分:0)
对HAML并不十分熟悉,但看起来您没有在视图中添加ID
。您的destroy.js.erb
正在寻找id=item-1
之类的选择器以隐藏它。因此,您的项目部分需要使用ID填充,以便稍后查找。在再培训局,我做:
<ul>
<% @items.each do |item| %>
<li id="item-" + item.id><%= item.name %> </li>
<% end %>
</ul>
类似的东西:)