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