我想将 css 类添加到与链接开头匹配的链接(使用 Javascript)。我的链接目前看起来像这样:
http://localhost/MainApp/User/UserEdit.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1
我只想查看 id 之前的部分:/MainApp/User/UserEdit.aspx
我已经有向链接添加 css 类的功能,它看起来像这样:
function markActiveLink() {
var path = location.pathname;
var home = "/";
$("a[href='" + [path || home] + "']").parents("li").each(function () {
$(this).addClass("selected");
});
}
location.pathname 的值为/MainApp/User/UserEdit.aspx
问题:如何修改我的函数 markActiveLink(),以便即使在链接的主要部分之后使用 id 也可以标记链接?
非常感谢这里的任何帮助!
最佳答案
使用starts with href 属性的选择器而不是精确选择器。
更改:
$("a[href='" + [path || home] + "']")
至
$("a[href^='" + [path || home] + "']")
要解决选择所有链接的主路径问题,请将 makeActiveLink 更改为如下:
function markActiveLink() {
var path = location.pathname;
var links = null;
if(path){
links = $("a[href^='" + path + "']");
} else {
links = $("a[href='/']");
}
links.parents("li").each(function () {
$(this).addClass("selected");
});
}
关于javascript - Javascript 中的正则表达式用于 trim 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6930485/