我试图将所有具有"option"类的元素的显示属性设置为"none",但随后我想提取我单击的元素,并将显示属性从"none"更改回"block"。
我想在vanillaJS中找到一个解决方案。
<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);
});
感谢
您的代码可以工作,但会做一些不必要的事情,如:
- 当您已经有了要附加事件的
document
对象时对document.querySelector('*')
的调用 - 当您已经有了指向单击的元素的
event.target
时,对document.getElementById(clickedId)
的调用 - 为单击的元素设置
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";
}
}
}
});
只需忽略被单击的那个。
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);
});
<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>