使用Rail的原型助手形成显示/隐藏效果

时间:2009-08-20 07:11:12

标签: javascript ruby-on-rails ruby forms prototype

我正在尝试创建一个与Reddit类似的线程评论系统:我在评论上单击“回复”,表单会显示出来。此表单有一个“取消”按钮,用于删除表单,返回原始状态。

我正在尝试使用一个link_to_function来添加表单,而表单本身有一个button_to_function来删除自身和表单。因此,link_to_function生成的javascript需要使用转义的javascript转义HTML ,并且由于某种原因,它无法正常工作(点击“回复”不会执行任何操作)。如果我不添加“取消”按钮,它工作正常。这就是我所拥有的:

<!-- comments/_comment.html.erb -->
<div id="comment_<%= comment.id %>">
  <%= h comment.content %>
</div>

<div id="reply_comment_<%= comment.id %>"></div>

<%= link_to_function 'Reply' do |page|
      page.replace_html "reply_comment_#{comment.id}",
        render(:partial => 'comments/form', :locals => {:comment => comment,
               :commentable => comment.commentable})
    end
%>

<!-- comments/_form.html.erb -->
<% form_tag(comments_path) do %>
  <%= hidden_field_tag 'comment[parent_id]', comment && comment.id %>
  <%= hidden_field_tag 'comment[commentable_id]', commentable.id %>
  <p>
    <%= text_area_tag 'comment[content]' %>
  </p>
  <p>
    <%= submit_tag 'Send' %>
    <% if comment %>
      <%= button_to_function 'Cancel' do |page|
            page.replace_html "reply_comment_#{comment.id}", ''
      end
       %>
    <% end %>

  </p>
<% end %>

我做错了什么?

2 个答案:

答案 0 :(得分:0)

虽然技术上可以完全按照您的指定进行操作,但我认为编码中存在一个错误,因为您在JavaScript中使用了JavaScript。我确定那里有一个Yo Dawg的笑话。内部JavaScript的第二位可能没有正确引用。

你可以做什么而不是使用replace_html函数只是将部分设置为隐藏,然后关闭和打开可见性。

或者,您可以尝试通过任何必要的方法修复编码。

我只是想在这里。如果您可以发布此输出,那么肯定会更容易说出来。

答案 1 :(得分:0)

我不确定为什么你在做什么不起作用,但这是另一种方法来做你想做的事情。您可以在该元素上执行显示/隐藏(我删除了表单内容,但格式大致相同),而不是从DIV内部插入和删除文本:

<!-- comments/_form.html.erb -->
   <%= button_to_function 'Cancel', "$('reply_comment_blah').hide()" %>
</p>

<!-- comments/_comment.html.erb -->
<div id="comment_blah">
  Hello!
</div>

<div id="reply_comment_blah", style="display: none;"><%= render :partial => 'form' %></div>

<%= link_to_function 'Reply' , "$('reply_comment_blah').show()" %>