切换除一个之外的所有内容,然后切换例外的除外

Toggle all except one and then toggle the excepted one?

本文关键字:然后 一个      更新时间:2023-09-26

我有这个问答部分。

我想做的是显示单击的那个并隐藏所有其他的。之后,如果我再次单击单击的那个,它将像其他人一样隐藏。

我已经完成了隐藏除第二次单击部分以外的所有部分。

标记

<h4 class=" question"><span class="glyphicon glyphicon-minus faq_icon"></span><strong>How r u?</strong></h4>
            <p class="answerswer">Fine</p>
            <h4 class=" question"><span class="glyphicon glyphicon-minus faq_icon" id=""></span><strong>What r u doing?</strong></h4>
            <p class=" answer">nothing.</p>

简讯

$(document).ready(function() {
    $(".question").click(function() {
        $('.answer').not(this).hide();
        $(this).next(".answer").toggle();
    });
});

现在我需要在第二次单击时隐藏THIS。怎么做?

检查一下

$(".question").click(function() {
    $('.answer').hide();
    if(!$(this).next(".answer").is(':visible')) {
        $(this).next(".answer").show();
    }
});
您需要

将当前answer元素传递给not()

单击处理程序中的thisquestion元素,因此$('.answer').not(this).hide();将隐藏所有answer元素,然后为当前 answer 元素调用 toggle 将始终显示它而不是切换它

$(document).ready(function() {
  $(".question").click(function() {
    var $ans = $(this).next(".answer").toggle();
    $('.answer').not($ans).hide();
  });
});
.answer {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4 class=" question"><span class="glyphicon glyphicon-minus faq_icon"></span><strong>How r u?</strong></h4>
<p class="answerswer">Fine</p>
<h4 class=" question"><span class="glyphicon glyphicon-minus faq_icon" id=""></span><strong>What r u doing?</strong></h4>
<p class=" answer">nothing.</p>

试试这个:

$(".question").click(function() {
    if( $(this).is(':visible') ){
        $('.answer').not(this).hide();
    }else {
         $('.answer').hide();
    }
    $(this).next(".answer").toggle();

});

相关文章: