简体   繁体   English

如何使用ajax和jQuery在循环中渲染部分内容?

[英]How to use ajax and jQuery to render partial in a loop?

I have tried to use ajax and jquery to render partial on-click. 我尝试使用ajax和jquery来呈现部分单击。 Please see Is it possible to render partial onclick without link_to? 请参阅是否可以在没有link_to的情况下呈现部分onclick? for details 详情

It works, the partial got rendered but it's not working correctly. 它可以工作,部分渲染,但是不能正常工作。

I've placed the link_to inside a loop but when the "New Comment" is clicked, it appear on the first post, when I clicked the "New Comment" on the second/third/fourth posts, all of the partials got render on the first post. 我已经将link_to放置在循环中,但是当单击“新评论”时,它出现在第一篇文章中,当我单击第二/第三/第四篇文章中的“新评论”时,所有的部分都将在第一篇文章。 What is going on? 到底是怎么回事?

Please see below my code. 请看下面我的代码。

Post/index.html.erb 邮政/ index.html.erb

<% @posts.each do |post| %>

   <%= post.title %>

   <%= post.content %>

   <%= link_to 'New Comment', new_comment_path, id: 'new_comment', remote: true %>

<% end %>

Comment/new.js.erb 注释/ new.js.erb

$('#new_comment').hide().after('<%= j render("form") %>')

_form.erb _form.erb

<%= form_for(@comment) do |f| %>

  <div>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </div>

  <div>
    <%= f.submit %>
  </div>

<% end %>

You are using the same ID for all your elements (Posts and New Comment Buttons) so when you click New Comment button all of the partials got render on the first post. 您对所有元素(“帖子”和“新评论”按钮)使用相同的ID,因此,当您单击“ 新建评论”按钮时,所有部分都在第一篇文章中呈现。 Because it is the first matching element found. 因为它是找到的第一个匹配元素。 You should use different element IDs for your posts so when clicking on New Comment you will know where (which post i mean)to render the form. 您应该为帖子使用不同的元素ID,以便在单击“新评论”时,您将知道在何处(我的意思是要呈现表单)。 for example you may use a counter like this: 例如,您可以使用如下计数器:

<%= link_to 'New Comment', new_comment_path, id: 'new_comment_' + i++, remote: true %> then all you have to do is to pass the elements id and change the following line: $('#'+PassedElementId).hide().after('<%= j render("form") %>') <%= link_to 'New Comment', new_comment_path, id: 'new_comment_' + i++, remote: true %>那么您要做的就是传递元素id并更改以下行: $('#'+PassedElementId).hide().after('<%= j render("form") %>')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM