Toggle class with jQuery

烂漫一生 提交于 2019-12-10 08:21:15

问题


I would need to hide a div when user clicks a link.

The html is something like this:

<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

As a default the comments are hidden (hence the class hidden there). Now if user clicks the Show/hide comments link it should show or hide comments for that specific item, depending are they visible or not. Now the question is do I need some id's to control js to hook only to that one specicif items ocmments and can I do it witouh id?

The js is something like atm:

$('.item .commentsToggle').click(function(){
        elem = $(this).parents('.item');

        $(elem).find('.comments').each(function() {
            $(this).toggleClass('hidden');
        });
    });

If there's only one item that works but if multiple it breaks up :/

This is pretty simple.. I just dont get it into my head how to do it actually :D


回答1:


http://jsfiddle.net/uB9Fb/

try this JS:

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



回答2:


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.




回答3:


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');
   });


来源:https://stackoverflow.com/questions/8295534/toggle-class-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!