目前,我有一个名为“评论”的按钮,当点击它时,它会滑下一个评论框。我希望每当用户单击页面上除注释框本身以外的任何区域时,都隐藏注释框。
目前,我的代码按钮只是消失时,点击它。有人能给我指个正确的方向吗?谢谢!
鲁比ERB:
<% @entry.each do |e| %>
<div class="entry">
<p><%= e.entry %></p>
<small>Posted by <%= e.author %> at <%= e.created_at.strftime("%I:%M%p %m/%d/%Y") %></small>
<% if e.comments.nil? %>
<p>No Comments</p>
<% else %>
<% e.comments.each do |c| %>
<div class="comment">
<blockquote><strong><%= c.author %></strong> writes:<%= c.comment %></blockquote>
</div>
<% end %>
<% end %>
<div class="comments">
<a href="#" data-comment="<%= e.id %>" class="newcommentbutton">Comment</a>
<div class="newcomment" id="comment<%= e.id %>">
<%= form_for @comment, :url => entry_comments_path(e, @comment) do |f| %>
<ol>
<li><%= f.label :author %>
<%= f.text_field :author %></li>
<li><%= f.label :comment %>
<%= f.text_area :comment %></li>
<%= f.submit %>
</ol>
<% end %>
</div>
</div>
</div>
<hr />
<% end %>
<%= button_to "Write A Message", new_entry_path, :method => :get %>
javascript代码:
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function()
{
$('.newcommentbutton').click(function()
{
var button = $(this);
var comment = button.attr('data-comment');
button.hide();
$('#comment' + comment).slideDown('fast', function() {
$('#comment' + comment + ' input[type=text]').focus();
});
});
$('.newcomment').click(function(event)
{
event.stopPropagation();
});
$('body').click(function()
{
$('.newcomment').hide();
});
});
最佳答案
您的新评论按钮还需要stop propagation,如下所示:
$('.newcommentbutton').click(function(e) {
var button = $(this);
var comment = button.attr('data-comment');
button.hide();
$('#comment' + comment).slideDown('fast', function() {
$('#comment' + comment + ' input[type=text]').focus();
});
e.stopPropagation();
});
你有正确的想法,只要记住
.newcommentbutton
也在<body>
中,所以它打开了评论表单,然后点击弹出并关闭它。