jquery Current Nav item selector

2019-07-29 10:27发布

问题:

I can't figure out how to use jQuery to style the current nav item. I've tried several tutorials and such to no avail. Any help would be appreciated. Thanks in advance.

    <div id="menu">
     <ul id="nav">  
      <li><a href="http://poolguys.jaredmc.com/index.php">Contact</a></li> 
      <li><a href="http://poolguys.jaredmc.com/index.php">Gallery</a></li>
      <li><a href="http://poolguys.jaredmc.com/pool_liners.php">Pool Liners</a></li>
      <li><a href="http://poolguys.jaredmc.com/services.php">Services</a></li>
      <li><a href="http://poolguys.jaredmc.com/about.php">About</a></li> 
      <li><a href="http://poolguys.jaredmc.com/index.php">Home</a></li> 
    </ul><!--end nav-->         
  </div><!--end menu--> 

   /** nav styling **/

   //<![CDATA[
    jQuery(function() {
     jQuery('#nav li').each(function() {
      var href = jQuery(this).find('a').attr('href');
      if (href === window.location.pathname) {
      jQuery(this).addClass('current');
       }
      });
    });  
  //]]>

回答1:

You can use the Attribute Equals Selector [name="value"] to find out the nav item with the current path.

$(document).ready(function () {
    var str = location.href.toLowerCase();
    var item  = $('#nav li a[href="' + str  + '"]');
    if(item.length){
        $("li.current").removeClass("current");
        item.parent().addClass("current");
    }
})

Demo: Fiddle



回答2:

I figured it out!! Thanks for your help Will.i.am and Arun.p. THe lines of code below is all I needed after giving body id's to each page.

     /** nav selector **/
     var bodyid = $('body').attr('id');  
     $('#main_nav ul li a.'+ bodyid).addClass('current');