在函数thirdNavFunction
的循环内部,我需要定位所有.third-nav
类,除了单击的一个,它需要在没有jQuery的情况下完成,我该怎么做?
var thirdNav = document.getElementsByClassName("third-nav");
for (var i = 0; i < thirdNav.length; i++){
thirdNav[i].addEventListener("click", thirdNavFuntion);
}
function thirdNavFuntion() {
for (i = 0; i < thirdNav.length; i++) {
thirdNav[i].parentElement.className = "";
}
if (this.parentElement.className === "") {
this.parentElement.className = "nav-sub-li-active";
} else {
this.parentElement.className = "";
}
}
在这里的代码中,我定位了所有.third-nav
div,但这并没有按预期工作,我需要排除被点击的那个。我希望这是有道理的。
答案 0 :(得分:0)
Array.from()
将thirdNav
转换为数组。filter()
方法过滤掉点击的元素。forEach
方法更改所有父元素的类名。function thirdNavFuntion() {
const elements = Array.from(thirdNav).filter(el => el !== this)
elements.forEach(el => el.parentElement.className = "")
}