问题
I want to Show/Hide multiple divs on the same class using jQuery toggle.
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>
回答1:
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();
});
Note: The ".comment" in prev()
is not needed in this case, but makes it more obvious.
e.g. this will do the same:
$(".button").click(function() {
$(this).prev().toggle();
});
来源:https://stackoverflow.com/questions/27785317/jquery-toggle-multiple-classes