jQuery, управляющий одиночными DIV с одним и тем же классом (братьями и сестрами?)

Я создаю модуль часто задаваемых вопросов для своего сайта и хочу иметь возможность управлять отдельными элементами на странице, даже если все они имеют один и тот же класс. Я считаю, что это относится к братьям и сестрам, с которыми я еще не знаком.

В основном я хочу, чтобы пользователь мог щелкнуть 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>

person zuk1    schedule 04.11.2008    source источник


Ответы (2)


Если я правильно понимаю ваш вопрос, вы должны начать с установки всех ответов как скрытых в css: .answer {display:none;}

Затем вы можете использовать jquery, чтобы показать правильный ответ на выбранные вопросы:

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

Изменить: вы также можете использовать .toggle() вместо .show() для отображения/скрытия.

person Pat    schedule 04.11.2008

Вероятно, вам следует проверить этот вопрос, где делается что-то подобное.

По сути, вам сначала нужно настроить идентификаторы для ваших элементов, чтобы вы могли идентифицировать отдельные элементы в установленных классах.

Затем вы можете добавить обработчик события щелчка, который установит выбранный элемент и покажет соответствующий ответ.

Вы можете увидеть синтаксис захвата одноуровневых элементов в здесь.

person YonahW    schedule 04.11.2008