Javascript Rails 4:在AJAX调用时将部分附加到隐藏的div

Javascript Rails 4:在AJAX调用时将部分附加到隐藏的div,javascript,jquery,ruby-on-rails,ajax,ruby-on-rails-4,Javascript,Jquery,Ruby On Rails,Ajax,Ruby On Rails 4,在我的Rails 4应用程序中,我有一个Post和一个Comment模型 一篇文章有许多评论,一篇评论属于一篇文章 用户可以在postshow.html.erb视图中使用表单创建新注释: <h2 class="center">COMMENT ON THIS POST</h2> <%= form_for [@post, @post.comments.build], remote: true do |f| %> <p>

在我的Rails 4应用程序中,我有一个
Post
和一个
Comment
模型

一篇文章
有许多
评论,一篇评论
属于一篇文章

用户可以在post
show.html.erb
视图中使用表单创建新注释:

<h2 class="center">COMMENT ON THIS POST</h2>
        <%= form_for [@post, @post.comments.build], remote: true do |f| %>
          <p>
            <%= f.text_area :body, id: 'new_comment_body', placeholder: "Write your comment here..." %>
          </p>
          <p>
            <%= f.submit "CREATE COMMENT", id: 'comment_submit' %>
          </p>
        <% end %>
通过AJAX调用,我能够将新创建的注释添加到页面:

# comments/create.js.erb

$('#post_show_comments').append("<%= j render @comment %>");
因此,在创建帖子的第一条注释时,它不会附加到div中,用户需要手动重新加载页面才能看到注释


如果还没有评论,我如何修改
comments/create.js.erb
文件的内容以显示
#post_show_comments
div,然后添加一条新评论?

按照Oscroaa的建议

<div id="post_show_comments_wrapper" style="<%= "display:none" if @post.comments.none? %>"> 
  <hr>
  <h2 class="center">COMMENTS</h2>
    <div id="post_show_comments">
      <%= render @comments %>
    </div>
</div>


评论
在我看来

# comments/create.js.erb
$('#post_show_comments_wrapper').show();
$('#post_show_comments').append("<%= j render @comment %>");
#注释/create.js.erb
$(“#post_show_comments_wrapper”).show();
$('post#u show_comments')。追加(“”);

另一个选项是重新构造视图UI,以便注释标题显示并显示“尚未注释”或“输入第一条注释”作为提示与表单一起显示。然后,列表的空div将被正常呈现和显示。

按照OscuroAA的建议

<div id="post_show_comments_wrapper" style="<%= "display:none" if @post.comments.none? %>"> 
  <hr>
  <h2 class="center">COMMENTS</h2>
    <div id="post_show_comments">
      <%= render @comments %>
    </div>
</div>


评论
在我看来

# comments/create.js.erb
$('#post_show_comments_wrapper').show();
$('#post_show_comments').append("<%= j render @comment %>");
#注释/create.js.erb
$(“#post_show_comments_wrapper”).show();
$('post#u show_comments')。追加(“”);

另一个选项是重新构造视图UI,以便注释标题显示并显示“尚未注释”或“输入第一条注释”作为提示与表单一起显示。然后,列表的空div将被正常呈现和显示。

在添加注释之前,是否可以使用jquery显示div?类似于$(“#post#u show_comments).show();当然。我应该在
$(“#post#u show_comments”)之前的
comments/create.js.erb
中插入这行代码吗?附加(“”;
?另外,我应该实现任何条件来检查div是否已经显示了吗?我实际上已经尝试过了(我在评论中提到的)它还不起作用。你的控制器是什么样子的?我刚刚用控制器中的代码更新了问题。但我不确定问题是否来自控制器,因为当一篇文章已经有评论时(因此,会显示
#post\u show\u comments
)一切都正常工作。我猜问题来自JS代码,但我不知道是怎么回事。在添加注释之前,可以使用jquery显示div吗?类似于$(“#post#show_comments)。show();当然我是否应该在
$(“#post_show_comments”)之前的
注释/create.js.erb
中插入这一行代码?另外,我是否应该实现任何条件来检查div是否已经显示?我实际上只是尝试了一下(我在评论中提到的),但它还没有工作。您的控制器看起来像什么?我刚刚用控制器中的代码更新了问题。但我不确定问题是否来自控制器,因为当帖子已经有评论时,一切都正常(因此,会显示
\post\u show\u comments
)。我猜问题来自JS代码,但我不知道是什么错了。