jquery Current Nav item selector

与世无争的帅哥 提交于 2020-01-15 23:34:42

问题


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');


来源:https://stackoverflow.com/questions/15452151/jquery-current-nav-item-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!