基于 URL 的主动导航

Active navigation based on URL

我的导航菜单是这样的

<div id="menu-div">
<ul>
<li><a href="localhost/admin/">Admin</a></li>
<li><a href="localhost/admin/page/">Pages</a></li>
<li><a href="localhost/admin/image/">Gallery</a></li>
<li><a href="localhost/admin/account/">Accounts</a></li>
<li><a href="localhost/admin/role">Roles</a></li>
<li><a href="localhost/admin/theme">Layout</a></li>
<li><a href="localhost/admin/backup">Backup</a></li>
</ul>
</div>

我想在 URL 的基础上向导航链接添加一个活动的 class。我尝试了以下 jQuery 函数

$(function () {
   $('#menu-div a[href^="/' + location.pathname.split("/")[1] +    '"]').addClass('active');
        });

此函数将所有链接设置为活动链接,而不仅仅是当前链接。 jQuery 函数一定有问题。我不太擅长。任何帮助将非常感激。谢谢。

JQuery 加载:

function() {
var whereAmI = window.location.pathname;
  switch(whereAmI){
    case "www.yourwebsite.com":
      /*do what you want*/
      break;
}    
}();

我不知道你正在使用的完整路径,所以我会编一个例子。假设您的路径是:

file:///Users/yourname/Desktop/test.html

当你打电话时:

location.pathname.split("/")

你得到一个如下所示的数组:

["", "Users", "yourname", "Desktop", "test.html"] 

然后,当您对该数组调用 [1] 时,您会得到第二个结果(索引从 0 开始),在本例中为:

Users

这不是你想要的。您正在寻找这样的路径:localhost/admin/。因此,根据您的实际路径,您可能正在寻找:

window.location.pathname

或整个路径减去协议:

window.location.hostname + window.location.pathname

您可以简单地将 location.pathname 与 jQuery 结束选择器 [ attr $=""] 一起使用,您可以使用它来搜索字符串中的子字符串。在这种情况下,您正试图找到指定的路径。这比 contains 更好,后者可以匹配类似的路径,例如

/管理员 /admin/foobar /foobar/admin

将全部匹配 /admin

稍等

这个解决方案太简单了。我们需要确保路径与提供的 href 完全匹配!

$(function () {
    (function(){   
       var path = location.pathname;
        $('#menu-div * a[href$="'+ path+'"]').each(function(index,element){
            var href = $(this).attr('href');
            if(href.indexOf('http://') !== -1){
                var exact = href.substring(7,href.length).split('/');
            }else{
                var exact = href.split('/');
            }
            exact[0] = '';//get rid of the host
            exact = exact.join('/');
            if(path == exact){
                $(this).addClass('active'); 
            }
        });
    })();
});

fiddle(请注意,您必须单击 运行,因为 jsfiddle.net 使用 javascript 作为实际路径名的别名。

如果你想激活同一个路径,当你点击这个路径的其他link时,

path= "/First" =>>> path for First will active.
path= "/First/Second" path for First will active too.



 $(document).ready(function () {
            var path = window.location.pathname;
            if (path != "/") {
                $("#menuitems li a[href*='" + path + "']").addClass("active");
                var arr = path.split('/');
                if (arr.length > 2) {
                    var pathtoactive = "/" + arr[1];
                    $("#menuitems li a[href*='" + pathtoactive + "']").addClass("active");
                }
            }
        });