2011-05-07 37 views
0
<!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> 

單擊問題後,我希望能夠顯示和隱藏重複答案。如果可能,請關閉其他打開的答案。無法在每個循環中顯示和隱藏div

我被困在這一點,不知道該怎麼做。

回答

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

這是您的點擊處理程序和所有。無需循環。

+0

此外,你不需要'style =「display:none;」'爲每個答案。只需將它添加到CSS中的「answer」類即可。 – morgar 2011-05-07 03:14:22

0

這會做你想要什麼,也隱藏其他答案:

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

希望這有助於。歡呼聲