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
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');
});
来源:https://stackoverflow.com/questions/8295534/toggle-class-with-jquery