如果它的 href 包含在窗口 href 中,如何将类添加到标题元素?



如果类的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");
});

一个示例标头 href 将是
http://localhost:8090/website/jobs.php
如果我的window.location.href完全匹配,它工作得很好。我遇到的问题是,如果我单击生成查询字符串的内容,例如

http://localhost:8090/website/jobs.php?info=54 然后刷新页面,标头元素将不再具有该类。是否可以
更改函数,以便如果标头元素的 href 包含在window.location.href中,它将添加类?还是根本没有查询字符串?

http://localhost:8090/website/jobs.php http://localhost:8090/website/jobs.php?info=54

您可以使用以下命令删除网址参数:url.replace(/?.*/,'')

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

您可以使用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");

最新更新