【问题标题】:How to add class to header element if its href is contained within window href?如果其href包含在窗口href中,如何将类添加到标题元素?
【发布时间】:2020-09-21 15:28:28
【问题描述】:

如果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.php
http://localhost:8090/website/jobs.php?info=54

【问题讨论】:

    标签: javascript html jquery href


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-10-22
        • 2023-03-07
        • 2013-03-30
        • 1970-01-01
        • 1970-01-01
        • 2019-08-22
        • 2014-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多