基于URL添加活动导航类 [英] Add Active Navigation Class Based on URL

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

问题描述

我试图根据网页加载时所在的网页,向相应的菜单列表项添加活动类(即class =active)。下面是我现在的菜单。我试过每一个代码段,我可以找到在这方面,没有什么工作。那么,有人可以简单地解释在哪里以及如何在javascript中添加以定义此任务?

I'm trying to add an "active" class (i.e. class="active") to the appropriate menu list item based upon the page it is on once the page loads. Below is my menu as it stands right now. I've tried every snippet of code I could find in this regard and nothing works. So, can someone please explain simply where and how to add in javascript to define this task?

<ul id="nav">
    <li id="navhome"><a href="home.aspx">Home</a></li>
    <li id="navmanage"><a href="manageIS.aspx">Manage</a></li>
    <li id="navdocso"><a href="docs.aspx">Documents</a></li>
    <li id="navadmin"><a href="admin.aspx">Admin Panel</a></li>
    <li id="navpast"><a href="past.aspx">View Past</a></li>
</ul>

这里是我在我的网站主人放在我的head标签的javascript的例子。我做错了什么?

Here is an example of the javascript that I'm putting in my head tag in my site master. What am I doing wrong?

<script type="text/javascript" charset="utf-8">
    $(document).ready(function () {

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


推荐答案

正在执行,则该页面正在重新加载,这将使活动类无效。你可能想做的是:

The reason this isn't working is because the javascript is executing, then the page is reloading which nullifies the 'active' class. What you probably want to do is something like:

$(function(){
    var current = location.pathname;
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

在某些情况下, (多个类似的链接),但我认为这可以为你工作。

There are some cases in which this won't work (multiple similarly pointed links), but I think this could work for you.

这篇关于基于URL添加活动导航类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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