javascript - 如何从使用 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>
解决方案
编辑 看起来您已经编辑了您的问题并删除了按 ID 查找的内容。您在标记
dropdown-content
与dropdowncontent
脚本中的类命名方面也存在一些不一致。我已经用以下假设更新了我的答案。
- 既然您说您
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>
注意:样式与问题无关,只是一些有用的视觉表示。希望这能给你一个想法
推荐阅读
- ios - 在 iOS 11.3 中,didReceiveNotification 函数没有在点击时调用
- javascript - Datepicker 不是 ajax 请求后的函数
- javascript - 试图在 PHP 中搜索表
- android - 从管理员中删除应用并卸载
- laravel - Laravel 5.4:groupedBy id 并计算每个产品的数量
- parsing - 如果没有提供值,Antlr 应该放置一些标记
- c# - MessagePack 反序列化从 Dictionary<,> 继承的类中的异常
- oracle - 异常:批处理期间发生错误:ORA-01427:单行子查询返回多于一行
- python - 将元素写入另一个文件中的列表
- c# - iTextSharp XMLParser.Parse 反复抛出并吞下异常