2013-12-19 19 views
0

我有一個包含許多帖子和許多評論的部分。我想在添加評論時通過UJS更新頁面。但是,現在,當我提交新評論時,它會創建一些額外的div元素(根據頁面上當前有多少評論表單)。我是UJS的新手,不確定如何遍歷DOM,因此我可以在其提交的表單上添加註釋。以下是我的代碼,任何幫助將不勝感激。注意:這是一個帖子部分,它在一個包含很多帖子的頁面中呈現,所以DOM上有多個'.comment-form'類。當頁面上有多個表單時,如何使用UJS在Rails 3.2中指定特定表單?

<article class="post speech-bubble-post"> 
    <header class="group"> 

    <div class="post-header-thumb"> 
     <a href="<%= user_url(post.user) %>"> 
     <img class="circular-thumb" src="<%= post.user.profile_photo(:thumb) %>" alt=""> 
     </a> 
    </div> 

    <div class="user-info"> 
     <div class="name"> 
     <%= post.user.full_name %> 
     </div> 
     <div class="role"> 
     <!-- user.role_in_course --> 
     </div> 
     <div class="post-time"> 
     posted <%= time_ago_in_words(post.created_at) %> ago 
     </div> 
    </div> 
    <% if post.user == current_user || post.course.has_write_permission?(current_user) %> 
     <div class="post-controls"> 
     <div class="post-edit"> 
      <%= link_to "Edit Post", edit_post_url(post) %> 
     </div> 
     <form class="post-delete" action="<%= post_url(post) %>" method="POST"> 
      <input 
      type="hidden" 
      name="authenticity_token" 
      value="<%= form_authenticity_token %>"> 

      <input 
      type="hidden" 
      name="_method" 
      value="DELETE"> 

      <input type="submit" value="Delete Post"> 
     </form> 
     </div> 
    <% end %> 
    </header> 

    <p class="post-content"> 
    <%= post.body %> 
    </p> 
</article> 

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

<form 
    class="comment-form" 
    action="<%= post_comments_url(post) %>" 
    method="POST" 
    data-remote="true"> 

    <input 
    name="authenticity_token" 
    type="hidden" 
    value="<%= form_authenticity_token %>"> 

    <label for="comment_body"></label> 
    <textarea rows="1" cols="50" name="comment[body]" id="comment_body"></textarea> 

    <input type="hidden" name="comment[post_id]" value="<%= post.id %>"> 

    <input type="submit" class="comment-submit-button" value="Comment"> 
</form> 

<script> 
$(document).ready(function(event) { 

    $(".comment-form ").on("ajax:success", function(event, data){ 

     var $form = $(this) 

     $form.prepend(data); 
     $form[0].reset(); 
    }); 
}); 
</script> 

回答

0

你可以做這樣的事情

<form id="post-<%= post.id %>" class="comment-form" ...> 

<form data-post_id="post-<%= post.id %>" class="comment-form" ...> 

然後挑選了JS,如果你願意的話。

+0

我會如何挑選與JS?我正在考慮將ID放在字段中,但在jQuery中,我如何指定要使用的ID?換句話說,$('。post - ?')。on('ajax:success'...)。 – evkline

+0

你有幾個選項。在這裏看到更多:http://stackoverflow.com/questions/15786523/dynamically-name-variables-javascript – tyler

+0

我的頭靠在牆上沒有意識到我可以在jQuery中使用ERB標籤。感謝您指出了這一點! – evkline

相關問題