Jquery 为什么这个ajax请求会用新提交的注释替换我的所有注释?

Jquery 为什么这个ajax请求会用新提交的注释替换我的所有注释?,jquery,ruby-on-rails,ruby,ajax,ruby-on-rails-3,Jquery,Ruby On Rails,Ruby,Ajax,Ruby On Rails 3,因此,我有一个表单,在提交评论时请求JS调用: <%= simple_form_for([@video, @video.comments.new], :remote => true) do |f| %> <%= f.association :comment_title, :collection => @video.comment_titles, :label => "Comment Title:", :include_blank => false %

因此,我有一个表单,在提交评论时请求JS调用:

<%= simple_form_for([@video, @video.comments.new], :remote => true) do |f| %>
  <%= f.association :comment_title, :collection => @video.comment_titles, :label => "Comment Title:", :include_blank => false %>
  <%= f.input :body, :label => false, :placeholder => "Post a comment." %>
  <%= f.button :submit, :value => "Post" %>
<% end %>
这将呈现此create.js.erb文件:

$(".comment_content").html('<%= escape_javascript(render(@comment)) %>');
$(".comment_form")[0].reset();
$(“.comment_content”).html(“”);
$(“.comment_form”)[0]。重置();
上面的create.js.erb文件将注释部分呈现在此文件中:

<% comment_title.comments.each do |comment| %>
     <div class="comment_content">
        <%= render comment %>
     </div>
<% end %>

为什么在这个AJAX请求中,我的所有评论都被新提交的评论所取代

以下是我的评论:

<%= link_to image_tag(comment.user.profile.photo.url(:tiny)), profile_path(comment.user.profile), :class => "comment_image" %>
<div class="textual_comment_content">
    <div class="comment_text">
        <span class="name_link">
            <%= link_to "#{comment.user.name}", profile_path(comment.user.profile), :class => "normal" %>
        </span>
        <%= comment.body.gsub("'",'&apos;').html_safe %>
    </div>
    <span class="comment_footer">
        <ul>
            <li class="list_style"><%= time_ago_in_words(comment.created_at) %> ago</li>
            <% unless current_user != comment.user %>
            <li><%= link_to "Delete", video_comment_path(:video_id => @video, :id => comment), :method => :delete, :class => "normal" %></li>
            <% end %>
        </ul>
     </span>
 </div>
“评论图像”%>
“正常”%>
  • @video,:id=>comment),:method=>:delete,:class=>“normal”%>

首先,您需要将包装div从第一个代码移动到部分代码:

<div class="comment_content">
</div>

然后在第一个/最后一个元素之前/之后插入html:

$(".comment_content:first").before('<%= escape_javascript(render(@comment)) %>');
$(".comment_content:last").after('<%= escape_javascript(render(@comment)) %>');
$(“.comment\u content:first”)。在(“”)之前;
$(“.comment_content:last”)。在(“”)之后;

尝试使用
append()
/
prepend()
而不是
html()
?只是这样做是行不通的。。。但是,如果其他一些东西也发生了变化,那么它不起作用是什么意思呢?使用firebug或类似工具来查看ajax调用返回了什么。。。这应该更清楚地指出问题所在。。。Khez建议的应该有效(使用html()只是要求替换所有内容)使用append()会弄乱布局这实际上会使视觉布局出错。我之所以发布我的评论,是因为你可能需要这些信息。另外,我不仅要循环浏览评论,还要先循环浏览评论标题。本质上,这是一个循环中的一个循环,因此我将属于其各自评论标题的所有评论都显示在它下面,并且每一列都属于不同的列标题。我接受了你的答案,因为我没有提供足够的信息,而你的答案基本上是正确的。但我在我的应用程序中找到了答案。
$(".comment_content:first").before('<%= escape_javascript(render(@comment)) %>');
$(".comment_content:last").after('<%= escape_javascript(render(@comment)) %>');