将活动类添加到下一个兄弟

时间:2017-04-20 09:53:55

标签: javascript css

有人可以帮我解决这个问题吗,我对JavaScript有点困惑。每当有人点击问题时,应该将活动的类名添加到下一个兄弟,但是如何修复它。请用普通的JavaScript。任何其他框架都不计算在内。

document.querySelector(".question").addEventListener("click", function() {
	if(this.classList.contains("active")) {
		this.classList.remove("active");
	} else {
		this.classList.add("active");
	}
});
.faq-block .question,
.faq-block .answer {
	border: 1px solid red;
	padding: 10px;
}

.answer {
  display: none;
 }

.active {
  display: block;
}
<div class="faq-block">
    <div class="question">How do I cancel my order</div>
    <div class="answer">Answer</div>
</div>

<div class="faq-block">
    <div class="question">I am not getting an internet connection from my second SIM card</div>
    <div class="answer">Answer</div>
</div>

<div class="faq-block">
    <div class="question">My charger does not work and my device would not charge properly</div>
    <div class="answer">Answer</div>
</div>

<div class="faq-block">
    <div class="question">My fingerprint scanner is not working and does not respond when touched</div>
    <div class="answer">Answer</div>
</div>

4 个答案:

答案 0 :(得分:0)

试试这个

document.querySelector(".question").addEventListener("click", function() {
    if(this.classList.contains("active")) {
        this.classList.remove("active");
        this.nextSibling.classList.add("active")
    } else {
        this.nextSibling.classList.add("active");
    }
});

我不知道为什么你需要做条件检查。但要回答你的问题,你可以使用nextSibling

答案 1 :(得分:0)

对CSS的简单调整就可以解决问题:

.question.active+.answer {
    display: block;
}

这将允许您在问题上设置“活动”类,并让它显示答案。

或者,对该类使用this.parentNode,然后CSS变为:

.faq-block.active>.answer {
    display: block;
}

我认为,这也传达了更多的意义。

答案 2 :(得分:0)

使用querySelectorAlldocument.querySelector只会选择第一个匹配的元素。

// get all matched element
var ques = document.querySelectorAll(".question")
// loop over the array to add event to each of the element    
ques.forEach(function(item, index) {
   // creating closure
  (function(i) {
    // adding event listerner to each element
    ques[i].addEventListener("click", function() {
      // this refers to the current selected element
      if (this.classList.contains("active")) {
        this.classList.remove("active");
      } else {
        this.classList.add("active");
      }
    });
  }(index)) // passing the index to target element in the array
})

DEMO

答案 3 :(得分:0)

首先document.querySelector(".question")返回第一个元素匹配选择器(documentation)。

如果我理解正确,你想将.active课程应用于答案,那么你就是:

document.querySelectorAll(".question")
        .forEach(element => element.addEventListener("click", function () {
                nextNode = this.nextElementSibling;
                if(!nextNode.classList.contains("active")){
                    nextNode.classList.add("active");
                }
                else{
                  nextNode.classList.remove('active');
                }
            })
        );

JSFiddle