我如何使jQuery主动状态导航与包含字符串的URL一起使用



我已经设置了一个jQuery Active状态导航,但是当He url中包含字符串时,我会遇到麻烦,使活动状态正常运行。当URL包含字符串(即?linkId = en)时,活动状态正常工作,但是我的大多数URL都包含用于跟踪源的字符串。

我已经设置了评论的干净演示,以便您可以看看。

单击此处进行演示

有什么想法?

尝试使用window.location.pathname而不是window.location.href,因为它提供了无查询字符串

的路径
$(function() {
    var url = window.location.pathname;
    var page = url.substr(url.lastIndexOf('/') + 2);
    target = $('#menu a[href*="' + page + '"]');
    $(target).addClass('active');
}); 

尝试

$(function () {
    var pathname = window.location.pathname;
    var page = pathname.match(//([^/]+.[^/]+)/)[1];
    var target = $('#menu a[href*="' + page + '"]');
    $(target).addClass('active');
});

更改:

var url = window.location.href;
var page = url.substr(url.lastIndexOf('/') + 2);
target = $('#menu a[href*="' + page + '"]');
$(target).addClass('active');

to:

var page = window.location.pathname;
target = $('#menu a[href*="' + page + '"]');
$(target).addClass('active');

window.location.pathname将仅检索URL的路径部分。

https://developer.mozilla.org/en-us/docs/web/api/urlutils.pathname

您确实应该将代码作为问题的一部分包括在内,因此,如果您更改或删除测试页面,则与其他搜索同一件事的人相关。

编辑:

您可以反向进行操作,检查您的任何链接是否与当前URL的起始路径匹配。

$('#menu a').each(function(index, element){
    if (window.location.pathname.indexOf(this.href) == 0) {
        $(this).addClass('active');
        return false;
    }
})

相关内容

最新更新