成功调用ajax后重新运行JavaScript

我有一个删除按钮,其中包含remote:true选项:

# _categories.html.erb  

我的destroy方法使用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  { "html":" 'categories', :content_type => 'text/html') %>" } 

现在我的问题是我在页面加载时运行了这个JavaScript,删除初始类别按预期工作……直到数据发生变化。 每次用户通过添加新类别或删除类别来更改数据时,我都需要再次运行此方法。 怎么样? 请善待你的帮助,我根本不懂JavaScript! 哈哈

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

完全index.html.erb:

 # index.html.erb    

prohibited this category from being saved:


$(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); }); });

我不知道如果我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(); }); 

希望能帮助到你 :)