2015-12-24 55 views
0

我的導航欄出現問題。我試圖做一個功能,當我點擊一個導航項時,它展開它的子項。這工作完美。當我點擊另一個導航項目時,它會摺疊前一個項目並展開當前項目。這也很完美。我最近添加了一項新功能,我希望當前的導航項目能夠保持它的外觀,使它看起來很活躍,如果你們明白我的意思。如何使導航項目再次處於不活動狀態?

所有我能想出是這樣的代碼,它確實做了一些我想要的東西,但它不單擊當前導航項目後再次提出的導航項目無效的,只有當我點擊一個新的。如果有任何不清楚的地方,我會提供一個鏈接。

$(function(){ 
    $(".main-nav").on("click",function(){ 
     $(this).siblings().find(".inner-nav").hide(); //collapse siblings 
     $(this).siblings().find('a').attr('id', ''); //make siblings inactive 

     $(this).find(".inner-nav").toggle(); //expand current item 
     $(this).find("a").attr('id','nav-active'); //make current item active 
     $(this).find("ul").find("a").attr('id',''); //remove the nav-active ID from the current items children, as it also will appear as active, which is not the desired functionality 
    }); 
}); 
+0

請給我鏈接。 –

+0

看起來像添加了一個ID「nav-active」,但隨後將其移出下一行。只是猜測,如果你能提供一個好的鏈接。 – Martin

+0

https://jsfiddle.net/mikoo1991/qyr3s0h1/embedded/result/ –

回答

0

試試這個:

$(function(){ 
    $(".main-nav").on("click",function(){ 
     $(this).siblings().find(".inner-nav").hide(); 
     $(this).siblings().find('a').attr('id', ''); 

     $(this).find(".inner-nav").toggle(); 
     //$(this).find("a").attr('id','nav-active'); 
    if ($(this).find("a").attr('id') == 'nav-active') { 
     $(this).find("a").attr('id',''); 
    } else { 
     $(this).find("a").attr('id','nav-active'); 
    } 
     $(this).find("ul").find("a").attr('id',''); 
    }); 
}); 

我說只是簡單的驗證:

if ($(this).find("a").attr('id') == 'nav-active') { 
    $(this).find("a").attr('id',''); 
} else { 
    $(this).find("a").attr('id','nav-active'); 
} 

fiddle

希望,我理解你的權利。

0

我真的不能得到你的觀點非常好,但讓我想..當你點擊任何一個孩子的崩潰整個股利。在這種情況下,你需要e.stopPropagation();

$(function(){ 
    $(".main-nav").on("click",function(){ 
     $(".inner-nav").not($(this).find(".inner-nav")).hide(); 
     $(this).find(".inner-nav").toggle(); 
    }); 
    $(".main-nav > ul > li > a").on('click' , function(e){ 
     e.stopPropagation(); 
     $(".main-nav > ul > li > a").not($(this)).attr('id' , ''); 
     $(this).attr('id' , 'nav-active'); 
    }); 
}); 

我希望這一個是你在尋找什麼

Working Demo

+0

謝謝你的幫助,但你沒有解決我的問題。它不是我的意思。我希望當前的項目顯示爲活動狀態,並且在再次單擊時顯示爲非活動狀態 –

相關問題