2013-11-02 35 views
0

這是我的javascript,它的效果很好,除非如果您單擊相同的鏈接兩次它切換。我如何避免這種情況發生?最終,我只是想顯示一個基於點擊項目的psection ...但是如果你點擊它兩次,它會切換。點擊兩次後鏈接切換

current = "intersitial"; // div with id="m0" is currently diplayed 
function show_or_hide (id) 
{ 
    if (current) //if something is displayed 
    { 
     document.getElementById (current).style.display = "none"; 
     if (current == id) //if <div> is already diplayed 
     {       
      current = 0; 
     } 
     else 
     { 
      document.getElementById (id).style.display = "block"; 
      current = id; 
     } 
    } 
    else //if nothing is displayed 
    { 
     document.getElementById (id).style.display = "block"; 
     current = id; 
    } 
} 

我的HTML是:

<ul> 
    <li onclick="show_or_hide('intersitial')"><span>intersitial</span></li> 
    <li onclick="show_or_hide('advancedDetail')"><span>advancedDetail</span></li> 
    <li onclick="show_or_hide('ultimateDetail')"><span>ultimateDetail</span></li> 
</ul> 

<div class="megamenu" id="intersitial">intersitial</div> 
<div class="megamenu" id="advancedDetail" style="display: none">advancedDetail</div> 
<div class="megamenu" id="ultimateDetail" style="display: none">ultimateDetail</div> 

回答

1

我從生硬的JavaScript(使用在線事件處理程序,onclickonfocusonblur等)建議更改,並改爲使用JavaScript綁定事件:

// use a function-name that's descriptive of what it does: 
function showOnly() { 
    // or you could use `document.getElementsByClassName('megamenu'): 
    var divs = document.querySelectorAll('div.megamenu'), 
     // gets the text from the 'span' of the clicked 'li' (the 'id' for later): 
     id = this.firstChild.textContent; 
    // iterates over each of the found '.megamenu' elements: 
    for (var i = 0, len = divs.length; i < len; i++){ 
     /* if the id of the current 'div' is the same as the text in the 'span' 
      display = block, otherwise display = none: 
     */ 
     divs[i].style.display = divs[i].id === id ? 'block' : 'none'; 
    } 
} 

// get the 'li' elements: 
var lis = document.querySelectorAll('li'); 

// iterate over those elements and bind an event-handler to them: 
for (var i = 0, len = lis.length; i < len; i++) { 
    lis[i].addEventListener('click', showOnly); 
} 

JS Fiddle demo

這種方法還可以避免亂拋垃圾的變量(這些變量很容易覆蓋其他函數,特別是(但不是唯一)當多個開發人員在同一個項目上工作時)。

參考文獻:

+0

太棒了!非常感謝你做的這些!!!! –

0
function show_or_hide(id) 
{ 
    if (current == id) return; 
    if (current) // if something is displayed 
    { 
     document.getElementById (current).style.display = "none"; 
    } 
    document.getElementById (id).style.display = "block"; 
    current = id; 
} 
+0

非常感謝!非常棒! –

+0

不客氣。我知道你的知識正在快速增長,不幸的是,你甚至無法幫助我輕鬆地幫助你。 – donkeydown