jQuery切换多个类 [英] jQuery toggle multiple classes
问题描述
我想使用jQuery切换在同一类上显示/隐藏多个div.
I want to Show/Hide multiple divs on the same class using jQuery toggle.
当前,该按钮显示/隐藏所有 div.如何在不使班级唯一的情况下使其切换一个div? 小提琴演示.
Currently, the button show/hides all divs. How can I make it toggle one div without making the class unique? Fiddle demo.
jQuery:
$(".button").click(function() {
$(".comment").toggle();
});
HTML:
<div class="comment">
Comment 1
</div>
<button class="button">Show Comment</button>
<br/>
<div class="comment">
Comment 2
</div>
<button class="button">Show Comment</button>
推荐答案
您需要找到与单击元素相关的注释.在您的情况下,它是按钮的前一个元素,因此将prev()
与$(this)
(单击的按钮)配合使用:
You need to find the comment relative to the element clicked. In your case it is the previous element to the button, so use prev()
with $(this)
(which is the button clicked):
JSFiddle:: http://jsfiddle.net/TrueBlueAussie/vgs2wsz2/1/
$(".button").click(function() {
$(this).prev(".comment").toggle();
});
注意:在这种情况下,不需要prev()
中的".comment",但使它更加明显.
Note: The ".comment" in prev()
is not needed in this case, but makes it more obvious.
例如会做同样的事情:
$(".button").click(function() {
$(this).prev().toggle();
});
这篇关于jQuery切换多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!