Javascript中的正则表达式修剪链接

时间:2011-08-03 17:20:10

标签: javascript asp.net regex

我想将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?

这里的任何帮助都非常感谢!

2 个答案:

答案 0 :(得分:4)

使用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");         
    });     
} 

答案 1 :(得分:0)

并非它是最佳解决方案,但您可以使用包含选择器:

$("a[href*='" + [path || home] + "']")