如果窗口的href中包含其href,如何向标题元素添加类?

问题描述 投票:0回答:1

我当前的代码将一个类应用于适当的标头元素,如果其hrefindexOf 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

javascript html jquery href
1个回答
0
投票

您可以使用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");
© www.soinside.com 2019 - 2024. All rights reserved.