我能够在子元素上添加和删除类,但所有类都是活动的。我想添加&一次只删除一个活动元素。我错过了什么?
<ul id="parent" class="container">
<li class="child"><a href="#one">one</a></li>
<li class="child"><a href="#two">two</a></li>
<li class="child"><a href="#three">three</a></li>
</ul>
document.addEventListener("DOMContentLoaded", function() {
const parent = document.querySelector('#parent');
parent.style.backgroundColor = 'blue';
const childrens = document.querySelectorAll('.child');
const child = document.querySelector('.child a')
Array.prototype.forEach.call(
document.querySelectorAll('.child'),
function(element) {
element.onclick = addActive;
}
);
function addActive(element){
element = this;
if(element.classList.contains('active')) {
element.classList.remove('active');
} else {
element.classList.add('active');
}
}
});
这里是:codepen
答案 0 :(得分:1)
现在,您只需从点击的元素中添加/删除活动类。在将单击的一个设置为活动状态之前,您必须从所有元素中删除该类。
e.g。
function addActive(element) {
element = this;
if (element.classList.contains('active')) {
element.classList.remove('active');
} else {
childrens.forEach(function(e) {
e.classList.remove('active');
});
element.classList.add('active');
}
}
答案 1 :(得分:0)
一种解决方案是首先从所有元素中删除active
类:
function addActive(element) {
childrens.forEach(function(elem) {
elem.classList.remove("active");
});
element = this;
if (element.classList.contains("active")) {
element.classList.remove("active");
} else {
element.classList.add("active");
}
}
答案 2 :(得分:0)
这也许是使用纯js切换子元素的最直接的方法。
<ul id="parent" class="container">
<li class="child"><a href="#one">one</a></li>
<li class="child"><a href="#two">two</a></li>
<li class="child"><a href="#three">three</a></li>
</ul>
<script>
//get children
var theChildren = document.querySelector('#parent').children;
//set event listener for to each child
function selectChild(child) {
child.addEventListener('click', function() {
var checkChildStatus = document.querySelector('#parent .selected');
if (checkChildStatus) {
checkChildStatus.classList.remove('selected');
}
child.classList.add('selected');
});
}
//loop through all children
[...theChildren].forEach(selectChild);
</script>