简单的手风琴不起作用,因为处理程序一次触发 2 次

Simple accordion doesn't work because handler fires 2 times at once

我正在尝试创建一个非常简单的手风琴。

index.html

    
    <div class="container">

        <div class="accordian">
            <div class="title">Title</div>
            <div class="body">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corrupti mollitia maxime ab. Possimus est optio 
        </div>
        <div class="accordian">
            <div class="title">Title</div>
            <div class="body">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corrupti mollitia maxime ab. Possimus est optio 
        </div>

    </div>

main.js

let accordians = document.querySelectorAll(".accordian")


const toggle = e => {
    if (e.target.nextElementSibling.classList.length < 2) {
        e.target.nextElementSibling.classList.add("hidden")
        console.log("1:",e.target.nextElementSibling.classList)
    }
    else {
        e.target.nextElementSibling.classList.remove("hidden")
        console.log("2:",e.target.nextElementSibling.classList)
    }
}

accordians.forEach((obj) => {
    obj.children[1].classList.add("hidden")
    obj.addEventListener('click', e => { toggle(e) }, false)
})

第一个手风琴没有任何问题,但是当点击“切换”功能上的第二个时,会立即触发两次,没有任何区别。有什么线索吗?

首先,您不需要为 classList 编写切换函数,因为它已经存在。

其次,您的 <div class="body"> 节点需要有结束 </div> 标签。

let accordians = document.querySelectorAll(".accordian")

accordians.forEach((obj) => {
    obj.children[1].classList.add("hidden")
    obj.addEventListener('click', e => {
      e.currentTarget.children[1].classList.toggle("hidden")
    }, false)
})
.hidden { display: none; }
<div class="container">

        <div class="accordian">
            <div class="title">Title</div>
            <div class="body">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corrupti mollitia maxime ab. Possimus est optio </div>
        </div>
        <div class="accordian">
            <div class="title">Title</div>
            <div class="body">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corrupti mollitia maxime ab. Possimus est optio </div>
        </div>

    </div>