Highlight Parent Link in Navigation Menu With Jque

2019-02-14 18:31发布

问题:

I'm using the following Jquery to highlight the link for the current page in my navigation.

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

My navigation looks like this:

<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>

The nav has a subnav for the "About Us" section.

I'd like to have the "About Us" Link receive the "active" class so it stays highlighted when I'm on one of its subnav pages.

So for example, if I'm on the "Sub Link 2" page, the About Us link is given an active class.

Can anyone point me in the right direction here?

Thanks for your help

回答1:

Try below code,

// 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    
}