如何将 .nextElementSibling 应用于下拉菜单的下一项

How to Apply .nextElementSibling to the next item of a dropdown menu

我有一个包含子项目的菜单,当我点击它们时,它会弹出显示项目。我设法打开了第一个项目,但我不能对第二个项目做同样的事情。我正在尝试为此使用 .nextElementSibling,但我不能。我做错了什么?

var dropdownBtn = document.querySelector('.menu-btn');

dropdownBtn.addEventListener('click',()=>{
var menuContent = document.querySelector('.drop_container');
    menuContent.classList.toggle("show");
  
})
.menu-btn {
  background: #e0e0e0;
  padding: 10px;
  margin: 5px 0px 0px 0px;
}

.menu-btn:hover {
  background: #000;
  color: #fff;
}


.drop_container {
   display: none;
   background-color: #017575;
   transition: 0.3s;
   opacity: 0;
}

.drop_container.show {
  display: contents;
  visibility: visible;
  opacity: 1;
}

.drop_container > .item {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  padding: 10px 0px 0px 0px;
}
<div class="dropdown-menu">

<div class="menu-btn">One</div>
<div class="drop_container">
  <a class="item" href="#">Contact Us</a>
  <a class="item" href="#">Visit Us</a>
</div>

<div class="menu-btn">Two</div>
<div class="drop_container">
  <a class="item" href="#">Contact Us</a>
  <a class="item" href="#">Visit Us</a>
</div> 

</div>

  1. 在 NodeList 中收集每个 .menu-btn,然后 运行 通过 .forEach()
  2. 在每次迭代中将 menuContent 引用为 this.nextElementSibling
  3. this是用户点击的.menu-btn,为了使用this不要使用箭头功能。如果您更喜欢箭头函数,请使用等效的(在这种情况下)e.target 代替 this.

const dropdownBtn = document.querySelectorAll('.menu-btn');

dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
  const menuContent = this.nextElementSibling;
  menuContent.classList.toggle("show");
}));
.menu-btn {
  background: #e0e0e0;
  padding: 10px;
  margin: 5px 0px 0px 0px;
}

.menu-btn:hover {
  background: #000;
  color: #fff;
}

.drop_container {
  display: none;
  background-color: #017575;
  transition: 0.3s;
  opacity: 0;
}

.drop_container.show {
  display: contents;
  visibility: visible;
  opacity: 1;
}

.drop_container>.item {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  padding: 10px 0px 0px 0px;
}
<div class="dropdown-menu">

  <div class="menu-btn">One</div>
  <div class="drop_container">
    <a class="item" href="#">Contact Us</a>
    <a class="item" href="#">Visit Us</a>
  </div>

  <div class="menu-btn">Two</div>
  <div class="drop_container">
    <a class="item" href="#">Contact Us</a>
    <a class="item" href="#">Visit Us</a>
  </div>

</div>