我正在尝试将所有具有“option”类的元素的display属性设置为“none”,但是我想提取我单击的元素并将display属性从“none”更改回“block” ”
我想在vanilla JS中找到解决方案。
<h1 class="option" id="header1">Header 1</h1>
<h1 class="option" id="header2">Header 2</h1>
<h1 class="option" id="header3">Header 3</h1>
<h1 class="option" id="header4">Header 4</h1>
<h1 class="option" id="header5">Header 5</h1>
document.querySelector('*').addEventListener('click', (event) => {
let clickedId = event.target.id;
let clickedClass = event.target.className;
if (clickedClass === "option") {
var list = document.querySelectorAll(".option");
for (var i = 0; i < list.length; i++) {
list[i].style.display = "none";
};
document.getElementById(clickedId).style.display = "block";
}
console.log(event.target.style.display);
});
由于
答案 0 :(得分:0)
忽略点击的那个。
document.querySelector('*').addEventListener('click', (event) => {
let clickedId = event.target.id;
let clickedClass = event.target.className;
if (clickedClass === "option") {
var list = document.querySelectorAll(".option");
for (var i = 0; i < list.length; i++) {
// ignore the one that was clicked
if (list[i] == event.target) continue
list[i].style.display = "none";
};
// document.getElementById(clickedId).style.display = "block";
}
// it is only useful if you display all the hidden again.
event.target.style.display = "block";
console.log(event.target.style.display);
});
&#13;
<h1 class="option" id="header1">Header 1</h1>
<h1 class="option" id="header2">Header 2</h1>
<h1 class="option" id="header3">Header 3</h1>
<h1 class="option" id="header4">Header 4</h1>
<h1 class="option" id="header5">Header 5</h1>
&#13;
答案 1 :(得分:0)
你的代码有效,但做了一些不必要的事情,比如:
document.querySelector('*')
对象时对document
的调用document.getElementById(clickedId)
指向所点击的元素时,对event.target
的调用display
样式为none
然后设置为block
理想情况下,如果可能,您应将click
事件附加到元素的最近父级。以下是我将如何重写您的代码:
let parent = document.querySelector("#all_options_parent") || document;
parent.addEventListener('click', (event) => {
if (event.target.className === "option") {
event.target.style.display = "block";
let allOptions = parent.querySelectorAll(".option");
for (let option of allOptions) {
if (option != event.target) {
option.style.display = "none";
}
}
}
});