代码之家  ›  专栏  ›  技术社区  ›  Learning

如果部分url匹配,则突出显示父菜单

  •  0
  • Learning  · 技术社区  · 6 年前

    <ul class="main-nav">
        <li> <a href="/en/" data-subnav="home-subnav" class="mm-nav-item"> HOME  </a> </li>
        <li> <a href="/en/latest/" data-subnav="newissue-subnav" class="mm-nav-item"> LASTEST UPDATES  </a> </li>
        <li> <a href="/en/categories/" data-subnav="categories-subnav" class="mm-nav-item"> CATEGORIES  </a> </li>
        <li> <a href="/en/news/" data-subnav="news-subnav" class="mm-nav-item"> NEWS  </a> </li>
        <li> <a href="/en/contact-us/" data-subnav="contact-subnav" class="mm-nav-item"> CONTACT US  </a> </li>
    </ul>
    

    有些页面有子页面,比如新闻页面有新闻详情页面和网址

    新页面=/en/news/

    new details page=/en/news/xxx/新闻标题

    所以我想突出显示父菜单 News 当有人在新闻详情页

     $(".main-nav li a").each(function () {
            //this part works when url matches
            if (this.href == window.location.href) {
                $(this).addClass("active-link");
            }
    
            //this part u want to match when part of url matchs
            if (window.location.href.indexOf('/news/') > 0) {
                $(this).addClass("active-link");
            }
        });
    

    下面是我想要的所有菜单的部分代码高亮 news 当任何一个用户在新的详细信息页上时要突出显示的菜单

    if (window.location.href.indexOf('/news/') > 0) {
                $(this).addClass("active-link");
            }
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   K K    6 年前

    您可以尝试从以下位置修改代码:

    if (window.location.href.indexOf('/news/') > 0) {
            $(this).addClass("active-link");
        }
    

    if (window.location.href.indexOf('/news/') > -1&&this.href.indexOf("/news/")>-1) {
          $(this).addClass("active-link");
    }
    
        2
  •  0
  •   Swanand Taware    6 年前

    $(".main-nav li a").each(function (e) {
            //this part works when url matches
           var attr = $(this).attr('href').toString();
            console.log(attr)
            //this part u want to match when part of url matchs
            if (window.location.href.indexOf(attr) > -1) {
                $(this).addClass("active-link");
    //To highlight parent use $(this).parent('li').addClass("active-link");
            }
        });
    
        3
  •  0
  •   pOoOf    6 年前

    尝试此代码

    $(".main-nav li a").each(function (index, element) {
        //this part works when url matches
        if (element.href == window.location.href) {
            $(element).addClass("active-link");
            return false;
        }
    
        //this part u want to match when part of url matchs
        if (window.location.href.indexOf('/news/') > 0) {
            $(element).addClass("active-link");
            return false;
        }
    });