添加&从导航链接中删除活动类 [英] Add & remove active class from a navigation link

查看:111
本文介绍了添加&从导航链接中删除活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找有关如何在链接中添加和删除类的教程,但遗憾的是没有成功。所有早期的问题都给了我一些理解,但没有给我我想要完成的结果。

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.

以下是我对JavaScript的看法:

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

        });
    });
});

这是我的导航:

<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 -->


推荐答案

您正在删除有效课程最近的 li 的子元素,然后你将活动类添加到当前的 a 的父元素。本着保持活跃类而不是列表项的精神,这对您有用:

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.

演示: http://jsfiddle.net/rq9UB/

这篇关于添加&amp;从导航链接中删除活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆