简体   繁体   English

根据点击切换特定的div,隐藏相同类别的所有其他div

[英]Toggle specific div based on click, hide all other divs of the same class

See my current code here: http://jsfiddle.net/swQLg/3/ 在这里查看我当前的代码: http : //jsfiddle.net/swQLg/3/

I have some div's like 我有一些像

<div class="qtn">question1</div>
<div class="ans">answer1</div>
<div class="qtn">question2</div>
<div class="ans">answer2</div>
<div class="qtn">question3</div>
<div class="ans">answer3</div>
<div class="qtn">question4</div>
<div class="ans">answer4</div>

my jquery function is 我的jQuery函数是

$(document).ready(function () {
    $(".qtn").on('click', function () {
        $(this).next(".ans").slideToggle();
    });
});

When I show one answer, I would like it to hide the other answers if they are showing. 当我显示一个答案时,如果它们显示了,我希望它隐藏其他答案。

Try this: 尝试这个:

$(document).ready(function () {
    $(".qtn").on('click', function () {
        var $ans = $(this).next(".ans");
        $ans.slideToggle(); //toggle the current one
        $(".ans").not($ans).slideUp(); //hide the others
    });
});

Fiddle 小提琴

The reason I save $(this).next(".ans"); 我保存$(this).next(".ans"); to a variable is for performance. 变量是为了性能。 If I didn't do this, every time that you call $(this).next(".ans"); 如果我没有这样做,那么每次您调用$(this).next(".ans"); , jQuery would have to wrap this into a jquery object and then perform the next() function on that jquery object. 是,jQuery将不得不包裹this成jquery对象,然后执行next()该jQuery对象上的功能。 In this case that would only be 1 extra time, but that still means 2 unnecessary operations. 在这种情况下,这仅是1个额外的时间,但这仍然意味着2个不必要的操作。

Here is a jsperf test demonstrating the difference. 这是一个展示差异的jsperf测试

Put slideUp() in your click event to slide everything up. slideUp()放入您的click事件中,以使所有内容向上滑动。 This will take care of closing/hiding already open divs and then put your code. 这将关闭/隐藏已经打开的div,然后放入您的代码。

Demo 演示版

$(document).ready(function () {
    $(".qtn").on('click', function () {
        $(".ans").not($(this).next(".ans")).slideUp(); // slide the rest up
        $(this).next(".ans").slideToggle();
    });
});

Edited to fix what @smerny pointed out. 编辑以修复@smerny指出的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM