问题
I have a simple piece of jQuery I'm using to toggle a div's visibility. It works well, however, when one div is toggled, other previously toggled divs stay open. Is there an easy way to update this script to close other divs when one is open?
jquery
$(document).ready(function(){
$(".member").click(function(){
$(this).next(".answer").slideToggle(100);
})
});
css
.answer {
display:none;
}
html
<div class="member">
<p>member 1</p>
</div>
<div class="answer">
<p>hidden content</p>
<div class="member">
<p>member 2</p>
</div>
<div class="answer">
<p>hidden content</p>
I'm not sure the best way to go about this. Should I append an active class to the active div? Or is there a simpler way one might go about this? Thanks!
回答1:
You can find any other answer element(other than the one targeted by clicked member element) which is visible and hide them
$(document).ready(function () {
var $answers = $('.answer');
$(".member").click(function () {
var $ans = $(this).next(".answer").stop(true).slideToggle(100);
$answers.not($ans).filter(':visible').stop(true).slideUp();
})
});
Demo: Fiddle
回答2:
Easy. Just hide all the .answer classes on click.. and then show only the one that was clicked on
$(".member").click(function(){
$(".answer").hide();
$(this).next(".answer").slideToggle(100);
})
回答3:
$(document).ready(function(){
$(".member").click(function(){
$(".answer").hide();
$(this).next(".answer").show(100);
})
});
Try the above
来源:https://stackoverflow.com/questions/21716954/close-toggled-div-when-another-is-opened-jquery