JQuery Управление одиночными DIV с одним и тем же классом (братья и сестры?)

StackOverflow https://stackoverflow.com/questions/261572

  •  06-07-2019
  •  | 
  •  

Вопрос

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

По сути, я хочу, чтобы пользователь мог щелкнуть на вопросном диве, а затем, когда он щелкнет по нему, ответ будет отображаться в том же самом диве, что и в вопросном диве (если это имеет смысл!). Любая помощь будет принята с благодарностью.

<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 (), чтобы показать / скрыть.

Другие советы

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

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

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

Синтаксис для захвата братьев и сестер можно найти в документации здесь .

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top