style.display =“block”表示event.target元素,style.display =“none”表示其他元素

时间:2017-10-27 10:33:03

标签: javascript for-loop event-handling getelementbyid addeventlistener

我正在尝试将所有具有“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);
});

由于

2 个答案:

答案 0 :(得分:0)

忽略点击的那个。

&#13;
&#13;
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;
&#13;
&#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";
            }
        }

    }
});