当另一个打开时关闭切换的div-jQuery [英] Close toggled div when another is opened - jQuery

查看:80
本文介绍了当另一个打开时关闭切换的div-jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的jQuery,用于切换div的可见性.但是,当切换一个div时,其他先前切换的div保持打开状态,效果很好.有没有简单的方法来更新此脚本以在打开一个div时关闭其他div?

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>

我不确定执行此操作的最佳方法.我应该将活动类添加到活动div吗?还是有一种更简单的方法可以解决这个问题?谢谢!

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();
    })
});

演示:小提琴

这篇关于当另一个打开时关闭切换的div-jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆