【问题标题】:Add class to nav if part of url matchs the menu items如果部分 url 与菜单项匹配,则将类添加到导航
【发布时间】:2018-08-27 01:21:34
【问题描述】:

假设我有以下主菜单结构,如果部分 url 与菜单链接匹配,我需要将类活动类添加到导航

例如 www.domain.com/en/blog/this-is-firt-blog 在这种情况下,我需要将 active 类添加到名称中的第二项 /blog

    <div class="wrapper">
    <ul>
<li><a href="/en/">Home</a></li>
    <li><a href="/en/blogs/" >All Blogs</a></li>
    <li><a href="/en/videos/" >All Videos</a></li>
    <li><a href="/en/contact/" >Contact Us</a></li>
    </ul>
    </div>

https://codepen.io/anon/pen/aYBzRd

我使用下面的代码来匹配 url 的部分 /blog 但这段代码将活动类添加到所有菜单项

 $(".wrapper li a").first().removeClass("active-menu");

        var pathnameurl = window.location.pathname;

        if (pathnameurl.indexOf('/blog') != -1) {
           // alert("match");

            $(".wrapper li a").each(function (index, element) {
                $(element).addClass("active");

            });
        }
        else
        {
            alert("nomatch");
        }

我尝试使用$(this).addClass("active");,但这也为所有菜单项添加了活动类

【问题讨论】:

  • 路径名是否总是以 /en/blog 或 /en/video 或 /en/contact 开头?
  • 它可以是 /en/blog//ar/blog//es/blog 因为这个原因我试图只匹配 /blog 部分
  • 但是你也可以有像 /en/video 或 /es/contact 这样的路径吗?

标签: javascript jquery html


【解决方案1】:

你为什么不试试这样的:

$('[href*=blog]').addClass('active')

https://codepen.io/kuzmanovic/pen/pLNJNo?editors=1111

附言您的 css 也需要更改才能工作

编辑:如果您需要在 css 选择器中添加斜杠:

$('[href*="/blog"]').addClass('active')

【讨论】:

  • 我尝试将其更改为 $('[href*=/blog]'),但它破坏了它。
  • 试试 $('[href*="/blog"]').addClass('active')
【解决方案2】:

使用这个

        $(".wrapper li a").removeClass("active");

        var pathnameurl = window.location.pathname; //'someurl/en/blogs/'

        $(".wrapper li a").each(function (index, element) {
              var $el = $(this);
              var href = $el.attr('href');

              if (pathnameurl.indexOf(href) >= 0)
                $el.addClass("active");

        });

https://codepen.io/anon/pen/eMBNMB

【讨论】:

  • 如果 (pathnameurl.indexOf(href) >= 0),这是主要的。 href 是元素的 href 属性值
  • 你要解释我哪一部分?
【解决方案3】:

确保从 a 标签中删除所有类

var pathnameurl = window.location.pathname;
if (pathnameurl.indexOf('/blog') != -1) {
    var elements = document.querySelectorAll(".wrapper li a");
    for(var i = 0; i < elements.length; i++) {
        if(elements[i].getAttribute("href").indexOf("/blog") > -1) {
            elements[i].className = "active";
        }
    }
} else {
    alert("nomatch");
}

或使用 jquery

$(".wrapper li a").first().removeClass("active-menu");
var pathnameurl = window.location.pathname;

if (pathnameurl.indexOf('/blog') != -1) {
    // alert("match");
    $(".wrapper li a").each(function (index, element) {
        if($(element).attr("href").indexOf("/blog") > -1)
            $(element).addClass("active");
    });
} else {
    alert("nomatch");
}

【讨论】:

    【解决方案4】:
    $(document).ready(function(){
    var pathnameurl = window.location.pathname;
    if (pathnameurl.indexOf('/blog') != -1) {
        $('a').each(function() {
            if($(this).attr("href") == "/en/blogs/") {
                $(this).parent().addClass("active")
            }
        }); 
    }
    else {
        alert("nomatch");
    } 
    });
    

    试试这个

    【讨论】:

    • 我必须根据href而不是.text()进行匹配,因为文本可以更改
    • @Learning 如果你回答了别忘了接受答案
    【解决方案5】:

    尝试对您的代码执行此操作:

    <div class="wrapper">
    <ul>
    <li><a id="x" href="/en/">Home</a></li>
    <li><a id="y" href="/en/blogs/" >All Blogs</a></li>
    <li><a id="z" href="/en/videos/" >All Videos</a></li>
    <li><a id="w" href="/en/contact/" >Contact Us</a></li>
    </ul>
    </div>
    

    然后在 javaScript 代码中试试这个:

    var pathname = window.location.href;
    if (pathname.indexof("/blogs") > -1){
        document.getElementById("y").classlist.add("active");
        document.getElementById("z").classlist.remove("active");
        document.getElementById("w").classlist.remove("active");
    }else if(pathname.indexof("/videos") > -1){
        document.getElementById("z").classlist.add("active");
        document.getElementById("").classlist.remove("active");
        document.getElementById("w").classlist.remove("active");
    }else if(pathname.indexof("/contact") > -1){
        document.getElementById("w").classlist.add("active");
        document.getElementById("y").classlist.remove("active");
        document.getElementById("z").classlist.remove("active");
    }
    

    如果您使用的是 word press 尝试:

    <div class="wrapper">
    <ul>
    <li><a href="/en/">Home</a></li>
    <li><a href="/en/blogs/" >All Blogs</a></li>
    <li><a href="/en/videos/" >All Videos</a></li>
    <li><a href="/en/contact/" >Contact Us</a></li>
    </ul>
    </div>
    

    你的 js 将是:

    var pathname = window.location.href;
    if (pathname.indexof("/blogs") > -1){
        var li = document.getElementsByTagName("li");
        for(var i = 0;i<li.length;i++){
            if(li[i].innerText === "All Blogs"){
                li[i].classlist.add("active");
            }else {
                if (li[i].classlist.contain("active")){
                    li[i].classlist.remove("active");
                }
            }
        }
    }
    

    这肯定能解决你的问题,祝你好运。

    【讨论】:

    • 不确定这是否实用,因为此菜单是数据库驱动的,并且不可能将 id 添加到每个 li
    • 感谢您的评论,但我的意思是将 id 放在“a”标签上,但您使用的是 word press 吗?
    【解决方案6】:

    试试这个

    $(".wrapper li a").first().removeClass("active-menu");
    
        var pathnameurl = window.location.pathname;
        $(".wrapper li a").each(function() {
            if(pathnameurl.indexOf($(this).attr("href")) != -1)
    
            {
                $(this).addClass("active");
            break;
            }
    
            else
        {
            alert("nomatch");
        }
        });
    

    【讨论】:

    • 这不起作用,因为菜单项具有例如href="/en/blogs/" 并且路径以 "/en/blog/" 开头。但绝对是正确的方法。
    • 我将如何匹配/blog/video 或者你在哪里匹配
    【解决方案7】:

    此代码适用于任何以 /xy/type 开头的 URL,其中 xy 是 2 个字母代码(例如 /en/blog...、/es/video...)。对于类似的表单,它应该很容易修改。

    // get the path name
    var pathnameurl = window.location.pathname;
    // extract the path type - assumes path is of the form /xy/type/...
    var pathtype = pathnameurl.replace(/^\/..\/([a-z]+).*$/, '$1');
    // now set the corresponding menu item active
    $('[href*=' + pathtype + ']').addClass('active');
    

    【讨论】:

      猜你喜欢
      • 2015-01-10
      • 1970-01-01
      • 2017-08-31
      • 2020-09-06
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多