Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top