简体   繁体   中英

How can I activate an element and deactivate others with Javascript

I'm working on a drop down FAQ where the user clicks the desire question and a hidden div containing the information is displayed. The piece of code I came up with only does that, displays or hides the clicked div. But I'm trying to do a function that one an user clicks the displayed information is hidden and the clicked one is shown. [activate one element and deactivate the rest] I do so through CSS adding/removing classes. I'm new to JS so there's things that takes me longer. If anyone can help me out it'll be amazing.

Here's the JS code so far.

//Storing the buttons
const questions = document.getElementsByClassName(‘faq-list-item’)
//Storing the hidden div
const clic = document.querySelectorAll(‘q-answered’)

for (let i = 0; i < questions.length; i++) {
   questions[i].addEventListener(‘click’,((e) => {
      return function() {
         if (clic[e].classList.contains(‘q-answered)) {
            clic[e].classList.replace(‘q-answered’, ‘q-answeredno’);
         } else if (clic[e].classList.contains(‘q-answeredno’)) {
            clic[e].classList.replace(‘q-answeredno’, ‘q-answered’);
         }
      }
   })(i))
}

The snippet below adds a click listener to each element of a list. The listener swaps the classes on every element, swapping to 'q-answered' if the element was clicked, swapping to 'q-answeredno' for the others.

(I think that's what you mean by "activating" some and "deactivating" the rest)

 // remove fromClass if it's on the element. add toClass function switchClass(element, fromClass, toClass) { if (element.classList.contains(fromClass)) element.classList.replace(fromClass, toClass); else element.classList.add(toClass); } const questions = [...document.getElementsByClassName('faq-list-item')]; questions.forEach(el => { el.addEventListener('click', e => { questions.forEach(q => { q === el? switchClass(q, 'q-answeredno', 'q-answered'): switchClass(q, 'q-answered', 'q-answeredno') }) }); });
 .q-answered { color: red; cursor: pointer; }.q-answeredno { color: blue; cursor: pointer; }
 <ul> <li class="faq-list-item q-answered">Item 0</li> <li class="faq-list-item q-answeredno">Item 1</li> <li class="faq-list-item q-answeredno">Item 2</li> <li class="faq-list-item q-answeredno">Item 3</li> <li class="faq-list-item q-answeredno">Item 4</li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM