문제

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!

도움이 되었습니까?

해결책

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

다른 팁

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);
})
$(document).ready(function(){
$(".member").click(function(){

    $(".answer").hide();

    $(this).next(".answer").show(100);
})
});

Try the above

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top