使用jQuery切换类 [英] Toggle class with jQuery
问题描述
当用户单击链接时,我需要隐藏一个div.
I would need to hide a div when user clicks a link.
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
默认情况下,注释是隐藏的(因此类隐藏在此处).现在,如果用户单击显示/隐藏评论"链接,则它应显示或隐藏该特定项目的评论,具体取决于它们是否可见.现在的问题是,我是否需要一些id来控制js使其仅挂接到该特定项目的项上,并且可以使用id来实现吗?
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?
js类似于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 :/
这很简单..我只是不明白它实际上是怎么做到的:D
This is pretty simple.. I just dont get it into my head how to do it actually :D
推荐答案
尝试使用此JS:
$('.commentsToggle').click(function(){
$(this).siblings(".comments").toggleClass('hidden');
});
这篇关于使用jQuery切换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!