0

I have the following script that adds a class to my navigation based on the URL.

var path = location.pathname.substring(1);
if (path) { 
    //Main NAV
    $('nav a[href$="' + path + '"]').parent().addClass('active');
    //Dropdown
    $('nav ul ul a[href$="' + path + '"]').parents(':eq(2)').addClass('active');
    //Side NAV
    $('aside li a[href$="' + path + '"]').parent().addClass('active');
};

It works on all pages but the home page. How would I adapt this to work on the home page also?

The HTML:

<ul class="left">
  <li><a href="/">Home</a></li>
    <li class="divider"></li>
  <li><a href="/about">About</a></li>
    <li class="divider"></li>
  <!-- MORE NAV -->
</ul>
4

1 回答 1

0

我认为这应该可以解决问题:

var path = location.pathname.substring(1);
if (path) { 
    if(path == "") {
       path = "/";
    }
    //Main NAV
    $('nav a[href$="' + path + '"]').parent().addClass('active');
    //Dropdown
    $('nav ul ul a[href$="' + path + '"]').parents(':eq(2)').addClass('active');
    //Side NAV
    $('aside li a[href$="' + path + '"]').parent().addClass('active');
};
于 2013-09-28T06:44:47.980 回答