如果 href 包含在 window href 中,如何将 class 添加到 header 元素?

How to add class to header element if its href is contained within window href?

我当前的代码将 class 应用于正确的 header 元素,如果它的 hrefindexOfwindow.location.href

$(function() {
    $('.sidebar-links li.active').removeClass("active");
    $('.sidebar-links li a').filter(function(){
        return this.href.indexOf(window.location.href) !== -1;
            }).parent().addClass("active");
});

一个示例 header href 将是
http://localhost:8090/website/jobs.php
如果我的 window.location.href 完全匹配,那就很好用了。我 运行 遇到的问题是,如果我单击生成查询字符串的内容,例如
http://localhost:8090/website/jobs.php?info=54
然后刷新页面,header元素不再有class。
是否可以更改函数,如果header元素的href包含在window.location.href 那它会加上 class 吗?或者根本没有查询字符串?
http://localhost:8090/website/jobs.php
http://localhost:8090/website/jobs.php?info=54

您可以使用 window.location.href.split('?')[0] 进行快速破解,

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams

如果你想要更花哨的解决方案

$('.sidebar-links li.active').removeClass("active");
$('.sidebar-links li a').filter(function () {
    return this.href.indexOf(window.location.href.split('?')[0]) !== -1;
}).parent().addClass("active");

您可以使用以下方法删除 URL 参数:url.replace(/\?.*/,'')

在您的代码中,将 this.href.indexOf(window.location.href) !== -1 更改为 this.href.indexOf(window.location.href.replace(/\?.*/,'')) !== -1