简体   繁体   English

如何使用 Javascript 激活元素并停用其他元素

[英]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.我正在处理一个下拉常见问题解答,其中用户单击期望问题并显示包含信息的隐藏 div。 The piece of code I came up with only does that, displays or hides the clicked div.我想出的那段代码只是这样做,显示或隐藏点击的 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.但我正在尝试做一个 function 用户单击显示的信息被隐藏并显示单击的信息。 [activate one element and deactivate the rest] I do so through CSS adding/removing classes. [激活一个元素并停用其余元素] 我通过 CSS 添加/删除类来实现。 I'm new to JS so there's things that takes me longer.我是 JS 的新手,所以有些事情需要我更长的时间。 If anyone can help me out it'll be amazing.如果有人可以帮助我,那将是惊人的。

Here's the JS code so far.这是到目前为止的JS代码。

//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.侦听器交换每个元素上的类,如果单击该元素,则交换为'q-answered' 'q-answeredno' ,其他元素则交换为“q-answeredno”。

(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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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