0

我在网络上下载的脚本有问题,基本上我需要的是折叠面板交互的常见问题解答问题,但在这种情况下,当我点击一个问题时,我想要的另一个问题不同,它打开,当我点击另一个问题时,之前的问题关闭并打开我点击的问题。

我找到了这个折叠面板脚本

它运作良好,但缺少一个细节,如果我点击同一个链接(问题),问题不会崩溃回到正常的正常模式,它只能关闭他选择另一个链接。当我选择另一个问题并且再次单击相同的问题时,我希望能够关闭该问题。

主页中的javascript代码:

<script type="text/javascript">
<!–
  $(function() {
    var $h2;
    var $answer;
    $(‘.answer’).hide();
    $(‘#faq h2′).bind(
        ‘click’,
        function()
        {
            if ($h2 && $h2[0] != this) {
                $answer.slideUp();
                $h2.removeClass(‘open’);
            }
            $h2 = $(this);
            $answer = $h2.next();
            $answer.slideDown();
            $h2.addClass(‘open’);
        }
    )
 });
 –&gt;
</script>

希望得到一些帮助

4

1 回答 1

0

首先,我重新修改了脚本的变量名称,稍微重构了它,并添加了注释以尝试更清楚地说明发生了什么:

<script type="text/javascript">
  $(function() { // onReady
    var $lastClickedH2;
    var $currentOpenAnswer;
    $('.answer').hide(); // All answers start hidden
    $(‘#faq h2′).click(function() // When an H2 is clicked
        {
            if ($lastClickedH2 && $lastClickedH2[0] != this) {
                // If there was an answer already open, close it
                $currentOpenAnswer.slideUp();
                $lastClickedH2.removeClass(‘open’);
            }
            // Set the last clicked H2/current open answer variables
            $lastClickedH2 = $(this);
            $currentOpenAnswer = $lastClickedH2.next();
            // Show the answer
            $currentOpenAnswer.slideDown();
            // Add an "open" class to the H2 (not sure why ...)
            $lastClickedH2.addClass(‘open’);
        }
    );
 });
</script>

如您所见(希望现在),当您单击已单击的 H2 时,它确实会关闭(通过 中的代码部分if),但之后的代码只是重新打开它。你想要做的是调整一些东西,使它不会重新打开;这是一种方法:

            ...
            if ($lastClickedH2 && $lastClickedH2[0] != this) {
                // If there was an answer already open, close it
                $currentOpenAnswer.slideUp();
                $lastClickedH2.removeClass(‘open’);
            }
            if ($lastClickedH2[0] == this) { // If we clicked on the same H2 twice
                // Unset the last clicked H2/current open answer variables
                $lastClickedH2 = undefined;
                $currentOpenAnswer = undefined;
                // Stop here
                // (Don't go on to the rest of the code, which would re-open it)
                return;
            }
            // Set the last clicked H2/current open answer variables
            $lastClickedH2 = $(this);
            ...

该代码应该可以工作,但它未经测试(因此,如果它有错误,请不要感到惊讶);希望它有所帮助。

于 2012-06-20T00:08:16.867 回答