我有一個簡單的下拉菜單使用JavaScript。多個下拉菜單使用相同的JS代碼
<div id="show-nav" class="dropdown">
<div id="dropdown" onClick="myFunction()">Menu Name</div>
<div id="myDropdown" class="dropdown-content">
<a href="#option1">Option 1</a>
<a href="#option2">Option 2</a>
<a href="#option3">Option 3</a>
</div>
</div>
而且JS:
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('#dropdown')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
我有幾個相鄰的div同一個菜單的多個副本。有了這段代碼,菜單在第一個元素中工作,但如果我嘗試在第二個元素中切換它,它只會在第一個元素中下降。我怎樣才能使這個工作在單個頁面上的幾個菜單?
'html'代碼會有幫助。 –