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
362 views
in Technique[技术] by (71.8m points)

javascript - Add & remove active class from a navigation link

I have been looking for tutorials on how to add and remove a class from a link unfortunately without any success. All the earlier questions on this have give me some understanding, but haven't give me the result I want to accomplish.

I'm trying to have an active state for my navigation, by adding and removing a class when the link is clicked.

Here is what I have as far as JavaScript:

$(document).ready(function(){

    //active state  
    $(function() {
        $('li a').click(function(e) {
            e.preventDefault();
            var $this = $(this);
            $this.closest('li').children('a').removeClass('active');
            $this.parent().addClass('active');

        });
    });
});

And this is my navigation:

<div id="nav">
    <div id="main-nav" class="center">
        <ul>
            <li><a href="/photography.php">Photography</a></li>
            <li><a href="/web.php">Web</a></li>
            <li><a href="/print.php">Print</a></li>

            <li class="nav-R"><a href="/about.php">About</a></li>
            <li class="nav-R"><a href="/contact.php">Contact</a></li>
        </ul>
    </div><!-- close center -->
</div><!-- close-nav -->
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're removing the 'active' class from the closest li's child element, and then you're adding the active class to the current a's parent li. In the spirit of keeping the active class on the anchors and not the list items, this will work for you:

    $('li a').click(function(e) {
        e.preventDefault();
        $('a').removeClass('active');
        $(this).addClass('active');
    });

The active link is the active link. There'd never be more than one link active at any given time, so there's no reason to be all specific about removing the active class. Just remove from all anchors.

Demo: http://jsfiddle.net/rq9UB/


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

...