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

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

问题描述

我正在尝试根据页面所在的页面将一个 active 类(即 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?

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

推荐答案

这不起作用的原因是因为 javascript 正在执行,然后页面正在重新加载,这使 'active' 类无效.您可能想要做的是:

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天全站免登陆