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

标签 javascript html css menuitem itemscontrol

我有一个包含子元素的菜单,当我单击它们时,它会弹出显示元素。我成功打开了第一个元素,但无法打开第二个元素。我尝试使用 .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>

关于javascript - 如何将 .nextElementSibling 应用于下拉菜单的下一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72337684/

相关文章:

javascript - getElementById 获取特定 html 标签

php - 收集用于ajax提交的表单数据

javascript - 无法在 Flash 文件上方获取 CSS 下拉菜单

css - 如何重置css字体缓存

javascript - 什么将取代 HTML & CSS & JS?

javascript - 使用gulp构建prod或dev代码时读取环境变量然后在客户端JS中替换它们

javascript - 将一个函数绑定(bind)到多个套接字

javascript - 在关闭按钮旁边的模式标题中 float 按钮

javascript - 一次打印一个数字

javascript - ng-repeat 更新所有表单