繁体   English   中英

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

[英]How do I make jQuery active state navigation work with URLs containing strings?

我已经设置了jQuery活动状态导航,但是当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');

至:

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;
    }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM