Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - Adding 'active' class current menu item w/ JQuery

There have been several SO solutions to this, but I haven't had any luck getting them to work. JQuery beginner trying to work through a solution to add an 'active' class to the active list item in a simple navigation menu:

   <div id="main-menu">

      <ul>
         <li><a href="/site/about">About Us</a></li>
         <li><a href="/site/work">Our Work</a></li>
         <li><a href="/site/contact">Contact Us</a></li>    
      </ul>

    </div>

A previous SO post indicated that this worked, but I've had no success so far. I'm using pretty permalinks in wordpress, so the full path to any page is like:

http://www.foobar.com/site/about/

This is my work so far:

<script>
$(function(){
    var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(//$/,''));    
        $('#main-menu li').each(function(){
            if(urlRegExp.test(this.href)){
                $(this).addClass('active');
            }
        });
});?
</script>

I've tried several solutions, including changing how I write the href, etc. The part of the code I'm really foggy on is the urlRegExp part...Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try with

    $('#main-menu li a').each(function(){
        if(urlRegExp.test(this.href)){

        ...
    });

instead of

    $('#main-menu li').each(function(){
        if(urlRegExp.test(this.href)){
        ...
    });

since href attribute you're looking on next line with this.href is applied on links, and not on list-items

then, if you need to apply the class active on <li> element just use

 $(this).parent().addClass('active'); 
 // or  $(this).closest('li').addClass('active');
 // or pure-JS : this.parentNode.className += 'active';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...