无法在每个循环中显示和隐藏div

时间:2011-05-07 03:08:38

标签: jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title></title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){


            $(".a_faq").each(function(i){

            $(this).find(".question").click(function(){ $(this).find(".answer").show();   });

            });



            });

        </script>
    </head>
    <body>

    <div class="a_faq">
        <div class="question">Where is everyone?</div>
        <div style="display:none;" class="answer">there</div>
    </div>
    <div class="a_faq">
        <div class="question">Where is the closest Starbucks</div>
        <div style="display:none;" class="answer">there</div>
    </div>
    <div class="a_faq">
        <div class="question">Where are my glasses?</div>
        <div style="display:none;" class="answer">there</div>
    </div>

    </body>
</html>

点击问题后,我希望能够显示和隐藏重复的答案。如果可能,请关闭其他已打开的答案。

我陷入困境,不知道该怎么做。

2 个答案:

答案 0 :(得分:3)

  $(document).ready(function() {
    $('.a_faq .question').click(function() {
      $(this).parent().find('.answer').toggle();
    });
  });

这是你的点击处理程序和所有。不需要循环。

答案 1 :(得分:0)

这将做你想要的,也隐藏其他答案:

$('.question').click(function() {
  var $answer = $(this).parent().find('.answer');
  if(!$answer.is(":visible"))
     $(".answer").hide();  //Hides the rest of the answers
  $answer.toggle();  
});

希望这会有所帮助。干杯