В моем классе JS мне поручили отредактировать приложение часто задаваемых вопросов, за исключением того, что одновременно может отображаться только один ответ. Другими словами, когда пользователь щелкает заголовок для отображения текста, другие ответы должны быть скрыты. Хоть убей, я не могу понять, что мне нужно сделать, чтобы закрыть другие заголовки.
"use strict";
var $ = function(id) { return document.getElementById(id); };
// the event handler for the click event of each h2 element
var toggle = function() {
var h2 = this; // clicked h2 tag
var div = h2.nextElementSibling; // h2 tag's sibling div tag
// toggle plus and minus image in h2 elements by adding or removing a
class
if (h2.hasAttribute("class")) {
h2.removeAttribute("class");
} else {
h2.setAttribute("class", "minus");
}
// toggle div visibility by adding or removing a class
if (div.hasAttribute("class")) {
div.removeAttribute("class");
} else {
div.setAttribute("class", "open");
}
};
window.onload = function() {
// get the h2 tags
var faqs = $("faqs");
var h2Elements = faqs.getElementsByTagName("h2");
// attach event handler for each h2 tag
for (var i = 0; i < h2Elements.length; i++ ) {
h2Elements[i].onclick = toggle;
}
HTML:
<h2><a href = "#" >What is JavaScript?</a></h2>
<div>
<p>JavaScript is a browser-based programming language
that makes web pages more responsive and saves round trips to the server.
</p>
</div>
<h2><a href = "#">What is jQuery?</a></h2>
<div>
<p>jQuery is a library of the JavaScript functions that you're most likely
to need as you develop websites.
</p>
</div>
<h2><a href = "#">Why is jQuery becoming so popular?</a></h2>
<div>
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
Конечно! Только что отредактировал основной пост.
И у вас есть полный контроль над javascript?
Я предполагаю, что нет явного постановления, говорящего, что я не лол



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Самый простой способ — начать со скрытого класса, скажем, .hide в содержании часто задаваемых вопросов, а затем, щелкнув соответствующий, удалить класс .hide, но непосредственно перед этим снова добавить его ко всем элементам.
<div id = "faq">
<h2>Question 1</h2>
<p class = "hide">Answer 1</p>
<h2>Question 2</h2>
<p class = "hide">Answer 2</p>
</div>
const questions = document.querySelectorAll('#faq h2');
const answers = document.querySelectorAll('#faq p');
questions.forEach(q => q.addEventListener('click', e => {
answers.forEach(a => a.classList.add('hide'));
e.target.nextElementSibling.classList.remove('hide');
}))
p.hide {
display: none;
}
Вы можете проверить код здесь: https://playcode.io/280470?tabs=console&index.html&output
Что-то вроде этого будет работать и довольно просто.
const hideAll = () => document.querySelectorAll('.answer').forEach(e => e.classList.add('hide'));
document.addEventListener('click', (e) => {
if (e.target.matches('a')) {
hideAll();
e.target.parentNode.nextElementSibling.classList.remove('hide');
}
});.hide {
display: none;
}<h2><a href = "#">What is JavaScript?</a></h2>
<div class = "answer">
<p>JavaScript is a browser-based programming language that makes web pages more responsive and saves round trips to the server.
</p>
</div >
<h2><a href = "#">What is jQuery?</a></h2>
<div id = "test" class = "answer hide">
<p>jQuery is a library of the JavaScript functions that you're most likely to need as you develop websites.
</p>
</div>
<h2><a href = "#">Why is jQuery becoming so popular?</a></h2>
<div class = "answer hide">
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>Спасибо! Я очень ценю это! Вы не представляете, как это помогает!
Удачного кодирования !!
Все заголовки h2. Можете ли вы опубликовать образец HTML?