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

基本上我希望用户能够点击问题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>
有帮助吗?

解决方案

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

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

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

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

其他提示

您应该查看问题,其中有类似的内容。

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

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top