将活动类应用于当前URL无效

时间:2016-08-26 13:28:34

标签: javascript jquery html gsp

我的项目中有一个侧边栏导航栏,我必须动态地将class="active"应用于每个href链接我应用了很多jquery / javasctipt函数但它不起作用且它是一个Groovy服务器页面(gsp)。 My url Links

到目前为止,我试过了

var activeurl = window.location;
$('#nav a[href="'+activeurl+'"]').parent('li').addClass('active');

第二个

$(function(){

var url = window.location.pathname, 
    urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
    // now grab every link from the navigation
    $('#nav a').each(function(){
        // and test its normalized href against the url pathname regexp
        if(urlRegExp.test(this.href.replace(/\/$/,''))){
            $(this).addClass('active');
        }
    });
});

第3个

$("#nav a").each(function() {   
if (this.href == window.location.href) {
    $(this).addClass("active");
   }
});

0 个答案:

没有答案