0

我有一个带有 remote: true 选项集的删除按钮:

# _categories.html.erb
<%= link_to 'Destroy', category, method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>

我的销毁方法使用 json:

# categories_controller.rb
  def destroy
    @category = Admin::Category.find(params[:id])
    @category.destroy
    save_to_history("The category \"#{@category.name}\" has been destroyed", current_user.id)

    respond_to do |format|
      # You can't retrieve the @categories before attempting to delete one. 
      @categories = Admin::Category.all

      format.json
    end
  end

我的 destroy.json.erb 文件看起来像:

#destroy.json.erb
<% self.formats = ["html"] %>
{
  "html":"<%= raw escape_javascript( render :partial => 'categories', :content_type => 'text/html') %>"
}

现在我的问题是我让这个 JavaScript 在页面加载时运行,并且删除初始类别按预期工作......直到数据发生变化。每次用户通过添加新类别或删除类别来更改数据时,我都需要再次运行下面的 JavaScript。如何?请善待您的帮助,我根本不懂 JavaScript!哈哈

  <script type='text/javascript'>

    $(function(){
      /* delete category */
      $('a[data-remote]').on('ajax:success', function(event, data, status, xhr){
        $("#dashboard_categories").html(data.html);
      });
    });

  </script>

完整的 index.html.erb:

# index.html.erb
<% title "Categories" %>

<%= form_for @category, remote: true do |f| %>
  <% if @category.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2>

      <ul>
      <% @category.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <table>
    <tr>
      <td><%= f.text_field :name, placeholder: 'Category Name' %></td>
      <td><%= f.text_field :color, placeholder: 'Colour' %></td>
      <td><%= f.submit %></td>
    </tr>
  </table>
  <br />
<% end %>


<div id="dashboard_categories">
  <%= render partial: 'categories' %>
</div>


<% content_for :javascript do %>
  <script type='text/javascript'>

    $(function(){

      /* new category */
      $('#new_admin_category').on('ajax:success', function(event, data, status, xhr){
        $("#dashboard_categories").html(data.html);
      });

      /* delete category */
      $('a[data-remote]').on('ajax:success', function(event, data, status, xhr){
        $("#dashboard_categories").html(data.html);
      });
    });

  </script>
<% end %>
4

1 回答 1

1

我不知道我是否 100% 了解你,但看起来你想在 AJAX 成功后添加事件?

$(function () {
    function InitializeEvents() {
        /* new category */
        $('#new_admin_category').on('ajax:success', function (event, data, status, xhr) {
            $("#dashboard_categories").html(data.html);
            InitializeEvents();
        });

        /* delete category */
        $('a[data-remote]').on('ajax:success', function (event, data, status, xhr) {
            $("#dashboard_categories").html(data.html);
            InitializeEvents();
        });
    }
    InitializeEvents();
});

希望能帮助到你 :)

于 2013-05-14T11:36:22.900 回答