使用jQuery切换类

使用jQuery切换类,jquery,show-hide,Jquery,Show Hide,当用户单击链接时,我需要隐藏一个div html是这样的: <div class="item"> <div class="entry"> Lorem ipsum </div> <a href="#" class="commentsToggle">Show/hide comments</a> <div class="comments hidden"> This comments div I want show/hide <

当用户单击链接时,我需要隐藏一个div

html是这样的:

<div class="item">
<div class="entry">
Lorem ipsum
</div>
<a href="#" class="commentsToggle">Show/hide comments</a>
<div class="comments hidden">
This comments div I want show/hide
</div>
</div>

<div class="item">
<div class="entry">
Lorem ipsum
</div>
<a href="#" class="commentsToggle">Show/hide comments</a>
<div class="comments hidden">
This comments div I want show/hide
</div>
</div>

....there's multiple items after this
如果只有一项有效,但有多项无效:/


这很简单。。我只是不知道该怎么做:D

如果你保持每个帖子的当前结构,最短的方法就是

$('.item .commentsToggle').click(function(){
    $(this).next().toggleClass('hidden');
});
但更一般的方法就像你建议的那样

$('.item .commentsToggle').click(function(){
    $(this).closest('.item').find('.comments').toggleClass('hidden');
});

还要注意的是,您应该使用
.on()
函数来绑定jQuery 1.7中的事件,即使旧的函数仍然可以工作。

我会像下面这样做

  $('.item .commentsToggle').click(function(){
        $(this).next('.comments').toggleClass('hidden');
   });
   $('.item .commentsToggle').click(function(){
        $(this).closest('.item').children('.comments').toggleClass('hidden');
   });
如果你有更多的意见,你可以使用以下

  $('.item .commentsToggle').click(function(){
        $(this).next('.comments').toggleClass('hidden');
   });
   $('.item .commentsToggle').click(function(){
        $(this).closest('.item').children('.comments').toggleClass('hidden');
   });

试试这个JS:

$('.commentsToggle').click(function(){
        $(this).siblings(".comments").toggleClass('hidden');
});

我没有发现代码有任何错误,它在这里工作正常: