Rails:使用slidetoggle进行Jquery Ajax问题

时间:2012-02-23 21:29:01

标签: ruby-on-rails ajax ruby-on-rails-3 jquery

我有一个评论部分,它是微博的一部分,我试图点击微博中的一个按钮,以便在CSS中显示为无滑动和显示的评论部分。问题是所有10个微博的评论按钮都会打开最新的微博,因为它应该打开它自己的微博评论部分。我不确定如何随着HTML改变javascript以使评论按钮动态显示它自己的微博。以下是我的工作,非常感谢任何帮助。谢谢。

JS

$(".CommentTitle").click(function(){
    $("#CommentContainer").slideToggle("slow", function(){ 
        $(".CommentTitle").html($(this).is(":hidden") ? "Comments" : "Comments");  
    });
});

HTML

<div class='Actions'>
<div class='CommentButton'>
<span class='CommentIcon'></span>
<span class='CommentNum'>5</span>
<span class='CommentTitle'>Comments</span>
</div>
</div>

<div id='CommentContainer' class='<%= micropost.id%>'>
<div class='Comment'>
<%=render "comments/form" %>
</div>
<div id='comments'>
<%=render @micropost.comments %>
</div>
</div>

2 个答案:

答案 0 :(得分:1)

$(".CommentTitle").click(function(){
    $("#CommentContainer", this.parent()).slideToggle("slow", function(){ 
        $(".CommentTitle", this).html($(this).is(":hidden") ? "Comments" : "Comments");  
    }); 
});

您可以向jQuery选择器添加上下文,以便它只匹配该元素下方。在这个例子中,我已经将this.parent()添加到容器选择器中,因此它只匹配单击容器内的#CommentContainer,并将其与标题选择器匹配,以便它匹配当前容器中的标题。

这假设您的微博HTML看起来像这样:

<div id='#CommentContainer'>
  <span class='CommentTitle'>Some clickable title</span>
  <p>data here</p>
</div>

元素类型无关紧要,只是CommentTitle是CommentContainer的直接子元素。

答案 1 :(得分:1)

更改HTML,以便在CommentContainer元素上没有重复的ID。这就是为什么jQuery只找到第一个 - 你正在创建无效的HTML。

假设每个微博都有一个注释按钮,你应该将微博ID作为数据属性添加到Title中,并检索它以找到正确的CommentContainer。每个评论容器都应该在其ID中包含它所属的微博的ID。

HTML:

<div class='Actions'>
    <div class='CommentButton'>
        <span class='CommentIcon'></span>
        <span class='CommentNum'>5</span>
        <span class='CommentTitle' data-micropost='<%= micropost.id %>'>Comments</span>
    </div>
</div>

<div id='CommentContainer-<%= micropost.id%>' class='CommentContainer'>
    <div class='Comment'>
        <%=render "comments/form" %>
    </div>
    <div id='comments'>
        <%=render @micropost.comments %>
    </div>
</div>

Javscript:

$(".CommentTitle").click(function(){
    var title = this;
    var postID = $(this).data('micropost');
    $("#CommentContainer-" + postID).slideToggle("slow", function(){ 
        $(".CommentTitle", title).html($(this).is(":hidden") ? "Comments" : "Comments");  
    }); 
});

更改CSS以隐藏.CommentContainer而不是#CommentContainer