动态常见问题解答点击失火

时间:2014-06-09 04:39:34

标签: jquery

我在 JavaScript和jQuery:The Missing Manual 这本书中做了这个例子,我们在其中构建了一个动态的FAQ部分。我们的想法是,当您单击某个问题时,会出现答案,如果您再次单击该问题,则答案将消失。我的问题是,有时我不得不点击两次问题来使答案显得/消失。就像点击事件没有随机触发一样。

以下是代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>A One Page Faq</title>
<link href="../_css/site.css" rel="stylesheet">
<script src="../_js/jquery-1.11.1.min.js"></script>
<style type="text/css">
h2 {
    background: url(../_images/open.png) no-repeat 0 11px;
    padding: 10px 0 0 25px;
    cursor: pointer;
}
h2.close {
    background-image: url(../_images/close.png);
}

.answer {
    margin-left: 25px;  
}
</style>

<script>
$(document).ready(function() {
  $('.answer').fadeOut(1);
  var hidden = true;

  $('.main h2').click(function() {
        if (hidden) {
            $(this).next('.answer').fadeIn();
            hidden = false;
        }
        else {
            $(this).next('.answer').fadeOut();
            hidden = true;
        }
    });

}); // end ready
</script>

</head>
<body>
<div class="wrapper">
<div class="header">
    <p class="logo">JavaScript <i>&</i> jQuery <i class="mm">The<br>Missing<br>Manual</i></p>
</div>
<div class="content">
<div class="main">
<h1>A One Page FAQ</h1>
<h2>I've heard that JavaScript is the long-lost fountain of youth. Is this true?</h2>
  <div class="answer">
  <p>Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)</p>
  </div>
<h2>Can JavaScript really solve all of my problems?</h2>
  <div class="answer">
  <p>Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.</p>
  </div>
<h2>Is there nothing JavaScript <em>can&#8217;t</em> do?</h2>
  <div class="answer">
  <p>Why, no there isn&#8217;t! It&#8217;s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that&#8217;s one smart programming language!</p>
  </div>
</div>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

问题是你为每个答案使用一个隐藏的标志......所以当你点击一个问题时,它会设置标志,然后当你点击另一个时,你首先要切换标志,然后它会在第二次点击时按预期工作。

可以像这样改进:

$(document).ready(function() {
  $('.answer').hide();


  $('.main h2').click(function() {
            $(this).next('.answer').slideToggle();
    });

}); // end ready

http://jsfiddle.net/wUTaS/1/

答案 1 :(得分:0)

使用以下代码,另请参阅评论

<script>
$(document).ready(function() {
  $('.answer').hide(); //on page load ...all answers will hide

  $('.main h2').click(function()//when you click on any question 
    { 

            $(this).next('.answer').toggle();//answer will hide /show



        });


}); // end ready
</script>