用于将 href 相对路径匹配到当前 URL 的正则表达式
我正在为没有任何服务器端功能的网站创建一个菜单。因此,我在菜单中动态突出显示当前页面的唯一方法(以及其他更改)是检查当前 URL 并将其与当前文件的路径进行比较;当它们匹配时,我添加“当前”类并更改一些其他属性的值。
问题是我的正则表达式仅匹配单个文件名的 href 值,而不是其他文件夹的相对路径。例如,如果我的菜单存储在“category”文件夹中,则 href="page.html"
将匹配“http://www.example.com/category/page.html”,但如果我使用了 href="../category/page.html"
它不匹配。如果我在 href 中使用根相对路径,也会出现同样的问题。
我当前的正则表达式是 /[^\/]+$/)[0]
。整个脚本如下所示:
$(document).ready( function () {
var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);
var currA = $("#nav-sub li a[href='" + pathname + "']");
var treeParent = currA.closest(".tree-parent");
treeParent.attr('aria-expanded', 'true');
currA.parents("li").addClass("current");
treeParent.children('a').first().attr('tabindex','0');
});
I'm creating a menu for a site that doesn't have any server-side capabilities. Because of this, my only way of highlighting the current page in the menu dynamically (among other changes) is to check the current URL and compare it against the path to the current file; when they match, I add a class of "current" as well as change the values of some other attributes.
The problem is that my regular expression only matches href values that are a single file name, not relative paths to other folders. For instance, if my menu is stored in the "category" folder, href="page.html"
will match "http://www.example.com/category/page.html" but if I used href="../category/page.html"
it wouldn't match. Same problem if I use a root relative path in the href.
My current regex is /[^\/]+$/)[0]
. Here's what the whole script looks like:
$(document).ready( function () {
var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);
var currA = $("#nav-sub li a[href='" + pathname + "']");
var treeParent = currA.closest(".tree-parent");
treeParent.attr('aria-expanded', 'true');
currA.parents("li").addClass("current");
treeParent.children('a').first().attr('tabindex','0');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在所有菜单超链接中使用根相对路径,那么您的整个情况会更容易处理。然后你可以与 window.location.pathname 进行比较。
假设这是不可能的,您可以使用 jq-uri 库来获取根相对路径来自您拥有的任何 href 的 javascript 中。它基本上是您正在寻找的正则表达式的库包装器。
要获取给定 href 的根相对路径,类似于:
要获得您想要的功能,您可以:
希望有帮助。
Your whole situation would be way easier to deal with if you just used root relative paths in all your menu hyperlinks. Then you could just compare against window.location.pathname.
Assuming that is not possible you can use the jq-uri library to get root relative paths in javascript from whatever href you have. It's basically a library wrapper around the regexs you are looking for.
To get the root relative path for a given href would be something like:
To get your desired functionality you could just:
Hope that helps.