Toggle class with jQuery

那年仲夏 提交于 2019-12-05 13:19:59

http://jsfiddle.net/uB9Fb/

try this JS:

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

If you keep the current structure of each post, the shortest way to do it is

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

But a more general way is like you're suggesting

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

Also note that you should use the .on() function to bind events as of jQuery 1.7, even though older functions still work.

I would do it like following

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

and if you have more comments you can use the following

   $('.item .commentsToggle').click(function(){
        $(this).closest('.item').children('.comments').toggleClass('hidden');
   });
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!