jquery append 在 Rails ajax 视图中不起作用



我的应用程序在带有jquery的Rails 4.1.1上。

该页显示活动列表,每个活动都包含在一个部分中。

对于每个活动,用户可以添加一个新注释 -- link_to new 注释方法的 id 基于活动 id 动态,即 #newcomment_185。

对于每个活动,注释显示在列表中,---ul的ID动态地基于活动ID,即#commentslist_185。

_activity.html.erb (my activity partial)
<p>The activity content is here.
<%= link_to t('new_comment'), new_activity_comment_path(activity_id: activity.id), :id => "newcomment_#{activity.id}", remote: true, :class => "button tiny " %></p>
<ul id="commentslist_<%= activity.id %> "> Comments: <%= activity.comments.count %>
 <% activity.comments.each do |comment| %>
    <li> <%= comment.body %> (par <%= comment.commenter.name %>) </li> 
<% end %>
</ul>
comments_controller.erb
class CommentsController < ApplicationController
load_and_authorize_resource
  def new
    @comment = Comment.new commenter: current_user, activity_id: params[:activity_id]
    respond_to do |format|
      if request.xhr?
        format.js
        format.html { render layout: false }
      else
        format.js { render :action => 'new' }
        format.html { render 'new' }
        format.json { render json: @comment }
      end
    end
  end
  def create
    @comment = Comment.new(comment_params)
    @comment.commenter = current_user
    respond_to do |format|
      if @comment.save
        format.js
        format.html { redirect_to root_path, notice: 'Commentaire ajouté' }
      else
        format.js { render 'update' }
        format.html { render 'new' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end
  private
  def comment_params
    params.require(:comment).permit(:body, :activity_id, :commenter_id)
  end
end
/app/views/comments/new.js.erb
$('#newcomment_<%= @comment.activity_id.to_s %>').hide().after('<%= j render("form") %>');
$('#commentform').slideDown(350);
/app/views/comments/create.js.erb
$('#commentform_<%= @comment.activity_id.to_s %>').remove();
$('#newcomment_<%= @comment.activity_id.to_s %>').show();
$('#commentslist_<%= @comment.activity_id.to_s %> ul').append('<%= j render(@comment) %>');

问题出在最后一行---除了这个之外,一切都有效。li 元素不会添加到 ul 中。

在Chrome控制台预览中,解析的js似乎还可以:

$('#commentform_188').remove();
$('#newcomment_188').show();
$('#commentslist_188 ul').append('<li> test 1 (by John Doe) </li>');

任何地方都没有错误消息。我已经尝试了最后一行的不同版本,---没有ul,交替使用单引号和双引号等。我毫无头绪。感谢您的任何指示。

我认为您添加了一个额外的空格来破坏您的选择器:

<="commentslist_<%= activity.id %> ">
<="commentslist_<%= activity.id %>">

最新更新