简体   繁体   中英

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

See my current code here: 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

$(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"); to a variable is for performance. If I didn't do this, every time that you call $(this).next(".ans"); , jQuery would have to wrap this into a jquery object and then perform the next() function on that jquery object. In this case that would only be 1 extra time, but that still means 2 unnecessary operations.

Here is a jsperf test demonstrating the difference.

Put slideUp() in your click event to slide everything up. This will take care of closing/hiding already open divs and then put your code.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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