2012-04-24 105 views
4

我正在使用以下jquery來突出顯示當前頁面在我的導航中的鏈接。使用jquery突出顯示導航菜單中的父鏈接

// Add Active Class To Current Link 
var url = window.location; // get current URL 
$('#nav a[href="'+url+'"]').addClass('active'); 

我的導航看起來是這樣的:

<nav> 
    <ul id="nav"> 
    <li><a href="">Home</a></li> 
    <li><a href="">About Us<b class="caret"></b></a> 
     <ul> 
     <li><a href="">Sub Link 1</a></li> 
     <li><a href="">Sub Link 2</a></li> 
     <li><a href="">Sub Link 3</a></li> 
     </ul> 
    </li> 
    <li><a href="">Products</a></li> 
    <li><a href="">Contact</a></li> 
    </ul> 
</nav> 

資產淨值有 「關於我們」 一節一subnav。

我希望「關於我們」鏈接收到「活動」類,以便它在我的某個subnav頁面上保持突出顯示。

因此,例如,如果我在「子鏈接2」頁面上,關於我們鏈接被賦予活動類。

任何人都可以在正確的方向指向我嗎?

感謝您的幫助

回答

5

嘗試下面的代碼,

// Add Active Class To Current Link 
var url = window.location; // get current URL 
$('#nav a[href="'+url+'"]').addClass('active'); 

var $activeUL = $('.active').closest('ul'); 
/* 
Revise below condition that tests if .active is a submenu 
*/ 
if($activeUL.attr('id') != 'nav') { //check if it is submenu 
    $activeUL 
     .parent() //This should return the li 
     .children('a') //The childrens are <a> and <ul> 
     .addClass('active'); //add class active to the a  
} 
相關問題