1

我正在为我的网站构建一个常见问题解答模块,我希望能够控制页面上的单个元素,即使它们都具有相同的类。我相信这属于我还不熟悉的兄弟姐妹。

基本上我希望用户能够单击问题 div,然后当他们单击它时,答案 div 与问题 div 设置显示在同一 div 中(如果这有意义!)。任何帮助将不胜感激。

<div class="set">
  <div class="question">What is the airspeed velocity of an unladen swallow?</div>
  <div class="answer">Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. </div>
</div>

<div class="set">
  <div class="question">What is the airspeed velocity of an unladen swallow?</div>
  <div class="answer">Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. </div>
</div>

<div class="set">
  <div class="question">What is the airspeed velocity of an unladen swallow?</div>
  <div class="answer">Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. </div>
</div>
4

2 回答 2

3

如果我正确理解您的问题,您应该首先将所有答案设置为隐藏在 css 中:.answer {display:none;}

然后您可以使用 jquery 显示点击问题的正确答案:

$(document).ready ( function () {
    $('.question').click(function() {
        $(this).next('.answer').show();
    });
});

编辑:您也可以使用 .toggle() 而不是 .show() 来显示/隐藏。

于 2008-11-04T11:35:13.783 回答
0

您可能应该查看这个问题,其中做了类似的事情。

基本上,您首先需要为您的元素设置 ID,以便您可以识别集合类中的单个元素。

然后,您可以添加一个单击事件处理程序,该处理程序将设置所选项目并显示适当的答案。

您可以在此处的文档中查看获取兄弟姐妹的语法。

于 2008-11-04T11:35:27.807 回答