2017-02-19 125 views
0

我有一個簡單的下拉菜單使用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同一個菜單的多個副本。有了這段代碼,菜單在第一個元素中工作,但如果我嘗試在第二個元素中切換它,它只會在第一個元素中下降。我怎樣才能使這個工作在單個頁面上的幾個菜單?

+2

'html'代碼會有幫助。 –

回答

0

您需要在代碼的兩個變化:

  • 使所有按鈕的onClick屬性相同。 (我想這是「myFunction();」)
  • 更改您的處理程序以處理實際單擊的按鈕。

這是可能與event.target:

function myFunction(event) { 
    event.target.classList.toggle("show"); 
} 
+0

目前所有的onClick屬性都是這樣的:

你是說我把上面的代碼替換掉了嗎?或者我需要補充一點? –

1

向該myFunctionthis。那就是:

<div id="dropdown" onClick="myFunction(this)">Menu Name</div> 

編寫JavaScript函數如下圖所示:

function myFunction(a) { 
    a.parentNode.getElementsByClassName("dropdown-content")[0].classList.toggle("show"); 
} 

不需要那麼多的JavaScript的:保持儘可能簡單。