0

我正在制作一个菜单,我想将 class="selected" 添加到活动菜单项中。当location.pathnameURL 类似于:- http://www.google.com/sub-folder/adrov48.php

所以它基本上只在 url 像这样简单时才有效: - http://www.google.com/adrov50.php

我知道有很多类似的问题,但是如果您查看下面的代码,我正在使用“新”方法,但它并没有真正起作用,那就是你们跳进去的地方:)

Javascript代码:

            var path = location.pathname;

            $("a[href='" + [path] + "']").parents("li").each(function() {   
                    $(this).addClass("selected");
            });

任何想法如何使这项工作成为可能,可以使用 jQuery。

如果有人认为我的方法不好或不理想,请告诉我原因并发布或链接我您的解决方案。

提前致谢!

4

2 回答 2

1

你为什么不做这样的事情:

// Check complete URL
var path = location.href;
$("#navID li a").each(function() {
    // Check if there is a match between the URL and the navigation link    
    if(path.match($(this).attr("href")) $(this).parent().addClass("selected");
});
于 2012-04-24T14:17:24.950 回答
1

结合 location.pathname 和 location.search 创建 URL 片段

于 2012-04-24T14:08:28.570 回答