弹出窗口中的Rails Ajax部分:重新打开popover时jQuery更改消失;更改仅显示在页面重新加载

时间:2014-12-17 13:30:56

标签: jquery ruby-on-rails ajax twitter-bootstrap

我有一部分我正在加载到弹出窗口的数据内容。在popover中,我对部分中的列表元素进行了ajax删除操作,该部分重新呈现新的更新部分。但是,当弹出窗口关闭并重新打开时,删除操作所做的jQuery更改将消失,而部分看起来就像删除从未发生过一样。为什么呢?

我的行动:

def destroy
  @notification = Notification.find(params[:id])
  @notification.destroy
  @notification.save

  @notifications = current_user.notifications
  respond_to do |format|
    format.js { render template: "notifications/destroy", :layout => false }
  end
end

我的destroy.js.erb

$('div#notifications-list').html($("<%= j render partial: 'notifications/notifications', locals: { notifications: @notifications } %>"))

点击此链接时会调用popover;这转发到行动index

<li><%= link_to current_user.notifications.where(read: false).count.to_s, notifications_path, :class => "glyphicon glyphicon-flag notifications", :title => 'Notifications', "data-content" => "#{render   partial: 'notifications/notifications', locals: { notifications: current_user.notifications }}" , rel:   'popover', 'data-toggle'=>"popover", id: 'notifications', remote: true %>
</li>

index行动:

def index
  @notifications = current_user.notifications

  @notifications.each do |notification|
    notification.update_attribute(:read, true)
  end

  @unread_count = @notifications.where(read: false).count

  respond_to do |format|
    format.js { }
  end
end

index.js.erb

$('#notifications').text('<%= j @unread_count.to_s %>');

弹出窗口在资产管道中的.js文件中调用,此处:

$(document).ready(function() {
  $("a#notifications").popover({ 
    trigger: 'click',
      'container': "body",
      'placement': "bottom",
    html: true}).on("show.bs.popover", function(){ $(this).data("bs.popover").tip().css("max-width",   "300px"); 
  });
});

开发日志说destroy.js.erb渲染得很好,与索引操作相同。但无论出于何种原因,直到页面重新加载在删除操作中完成的jQuery都没有显示。我已经尝试了很多东西,但我真的无法弄清楚为什么这不是工作。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,并在此处发布,以防有​​人遇到类似问题。只需要使用index.js.erb中的索引操作更新的@notifications替换div:

$('div#notifications-list').html($("<%= j render partial: 'notifications/notifications', locals: { notifications: @notifications } %>"))