首页 > 解决方案 > 如何从使用 while 循环呈现的多个下拉菜单列表中仅打开单击的下拉菜单

问题描述

我只想打开单击的下拉菜单。我认为在 while 循环中更新函数或下拉列表的 ID 存在问题。

这是我的 HTML:

<div class="dropdown">
  <td>
    <button onclick="myFunction(this)" class="dropbtn">
      <img src="images/options.png" width="8" height="8" />
    </button>
  </td>
  <i class="fas fa-caret-down"></i>
  <td>
    <div
      id="myDropdown"
      class="dropdown-content"
      style="border-radius:15px;"
    ></div>
  </td>
</div>

这是javascript:

<script>
  function myFunction() {
    var dropdown = document
      .getElementsByClassName('dropdowncontent')
      .classList.toggle('show');
  }
</script>

标签: javascript

解决方案


编辑 看起来您已经编辑了您的问题并删除了按 ID 查找的内容。您在标记dropdown-contentdropdowncontent脚本中的类命名方面也存在一些不一致。我已经用以下假设更新了我的答案。

  • 既然您说您dropdowns在 while 循环中获取,我假设有多个下拉菜单,每个下拉菜单都有一个切换按钮来显示或隐藏该特定下拉菜单的内容。所以我复制了标记来反映这一点。
  • 使用具有 onClick 功能的按钮,可能不需要getElementsByClassName而是使用目标按钮的父级并切换它的类,然后用于css显示或隐藏子内容。

function myFunction(thisButton){
  // Use the this context object to get the target/clicked button
  // Then find its parent
  var dropdownParent = thisButton.parentElement;
  
  // Toggle the class of that parent with a class that displays the content
  dropdownParent.classList.toggle("show");
}
.dropdown {
  border: solid 1px gray;
  padding: 10px;
  margin-bottom: 10px;
}
.dropdown button {
  padding: 10px;
  margin-bottom: 10px;
}


.dropdown-content {
  border: solid 1px black;
  height: 40px;
  background: #eee;
  padding: 10px;
  display: none;
}

.dropdown.show {
  background: #fef;
}
.dropdown.show .dropdown-content {
  display: block;
}
<div class="dropdown">
  <td>
    <button onclick="myFunction(this)" class="dropbtn">
      <img src="images/options.png" width="8" height="8" />
      Toggle Dropdown 1
    </button>
  </td>
  <i class="fas fa-caret-down"></i>
  <td>
    <div
      // You say you are returning multiple dropdowns, remove the id then
      id="myDropdown"
      class="dropdown-content"
      style="border-radius:15px;"
    >Dropdown 1 Content</div>
  </td>
</div>

<div class="dropdown">
  <td>
    <button onclick="myFunction(this)" class="dropbtn">
      <img src="images/options.png" width="8" height="8" />
      Toggle Dropdown 2
    </button>
  </td>
  <i class="fas fa-caret-down"></i>
  <td>
    <div
      class="dropdown-content"
      style="border-radius:15px;"
    >Dropdown 2 Content</div>
  </td>
</div>


注意:样式与问题无关,只是一些有用的视觉表示。希望这能给你一个想法


推荐阅读