Close toggled div when another is opened - jQuery

巧了我就是萌 提交于 2019-12-25 02:12:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!