我当前的代码将一个类应用于适当的标头元素,如果其href
是indexOf
window.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.phphttp://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");