从不同的div问题中切换类

时间:2012-04-11 23:30:38

标签: jquery selector

所以我有一个页面显示多个“帖子”,其中包含“评论”。我的代码:

<div class="post">
    This is a post
    <span class="toggleComments">Hide/Show Comments</span>
    <div class="comment">This is a comment</div>
</div>
<div class="post">
    This is another post
    <span class="toggleComments">Hide/Show Comments</span>
    <div class="comment">This is another comment</div>
    <div class="comment">This is a third comment</div>
</div>

所以这是我的问题:我有一个包含类toggleComments的范围,其中“切换”注释div。我通过以下方式实现了这一目标:

$('.toggleComments').click(function(){
    $('.comment').toggle();
});

通过点击链接,.comment div形式所有注释隐藏/显示,是否有一种方法可以使相同帖子的注释切换效果,而不是来自所有的帖子?

编辑:更新了.toggleComments行

5 个答案:

答案 0 :(得分:0)

尝试:

$('.toggleComments').click(function(){
    $(this).siblings('.comment').toggle();
});

更新以反映OP更新的HTML。

答案 1 :(得分:0)

假设.toggleComments位于您要切换评论的同一.post内,您会找到父.post,然后在其中找到要切换的相应评论:

$('.toggleComments').click(function(){
    $(this).closest(".post").find(".comment").toggle();
});

从其他答案中可以看出,有很多方法可以在同一个包含div中查找.comment个对象。这样做而不是引用兄弟姐妹的优势在于它会在公共.post父级的任何地方找到它们,即使将来某种程度上调整HTML的布局也是如此。我更喜欢使这种类型的代码尽可能强大,以防止未来的HTML调整,只要它不会危及任何重要的事情。

答案 2 :(得分:0)

我认为你应该这样做。 Demo here

$('.toggleComments').click(function(){
    var thisParent = $(this).parents('.post');
    thisParent.find('.comment').toggle();
});​

答案 3 :(得分:0)

<强> DEMO JSBIN

如果你有类似的话:

<div class="post">
    This is a post
    <div class="toggleComments">SHOW COMMENTS</div>
    <div class="comment">This is a comment</div>
</div>

......比这更有帮助。

$('.toggleComments').click(function(){
    $(this).nextAll('.comment').toggle();
});

答案 4 :(得分:0)

这种情况正在发生,因为您的所有“.comment”和“.toggleComments”都是相同的选择器。

如果您将这些更改为唯一,则可以使用。即:

<div class="post-1">
    This is a post
    <a class="toggle-1">Toggle Comments</a>
    <div class="comment-1">This is a comment</div>
</div>
<div class="post-2">
    This is a post
    <a class="toggle-2">Toggle Comments</a>
    <div class="comment-2">This is a comment</div>
</div>
$('.toggle-1').click(function(){
    $('.comment-1').toggle();
});
$('.toggle-2').click(function(){
    $('.comment-2').toggle();
});

这是jsfiddle http://jsfiddle.net/Uh9hJ/

编辑:使用兄弟姐妹是一个更好的顺便说一句,这个人说得对:https://stackoverflow.com/a/10115482/864488

相关问题