使用Jquery在导航菜单中突出显示父链接

C D*_*Dog 4 navigation jquery

我正在使用以下Jquery来突出显示导航中当前页面的链接.

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

我的导航看起来像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

导航具有"关于我们"部分的子视图.

我希望"关于我们"链接接收"活动"类,以便在我的某个子查询页面上时它会保持突出显示.

例如,如果我在"子链接2"页面上,则"关于我们"链接将被赋予活动类.

任何人都能指出我在正确的方向吗?

谢谢你的帮助

Sel*_*gam 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    
}
Run Code Online (Sandbox Code Playgroud)