将类添加到包含指向当前页面的菜单链接的 li

Add class to the li that contains the menu link to the current page

本文关键字:菜单 链接 li 当前页 添加 包含指      更新时间:2023-09-26

我有下面的菜单,我想将类active添加到包含用户当前正在查看的页面链接的<li>

<ul class="sidebar-menu">
<li class="treeview"><a href="#"><i class="fa fa-dashboard"></i> <span>Text</span></a></li>
<li class="treeview"><a href="#"><i class="fa fa-th"></i><span>Subtext 1</span><i class="fa fa-angle-left pull-right"></i></a>              
   <ul class=" treeview-menu">
      <li><a href="#"><i class="fa fa-circle-o"></i> Text 1</a></li>                
      <li><a href="#"><i class="fa fa-circle-o"></i> Text 2</a></li>
   </ul>
</li>
</ul>

我尝试了这个jQuery代码,但它对我不起作用:

$(function(){
var url = window.location.pathname, 
    urlRegExp = new RegExp(url.replace(/'/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
    // now grab every link from the navigation
    $('.treeview a').each(function(){
        // and test its normalized href against the url pathname regexp
        if(urlRegExp.test(this.href.replace(/'/$/,''))){
            $(this).addClass('active treeview-menu');
        }
    });
});

为了完成这项工作,我对你的代码做了一些更改:

  • 我没有将类添加到a,而是按照您的指定将其添加到li
  • 我没有使用正则表达式,而是使用自定义函数来删除前导斜杠和尾随斜杠。(不确定这样做是否绝对必要,但它不会造成伤害。
  • 您需要将类treeview添加到所有li中,如果这是您要在选择器中使用的类。
  • 我没有使用 href 属性,
  • 而是使用 pathname 属性来获取链接的 URL,因为它需要与函数顶部的location.pathname匹配。当然,您也可以与主机名进行比较,关键是您需要将苹果与苹果而不是橙子进行比较。
$(function(){
    //Use the function removeSlash to clean up URL instead of using RegExp.
    var url = removeSlash(window.location.pathname);
    //Loop through the treeview elements (the li) instead of the a.
    $('.treeview').each(function(){
        //Find the href of the a in the li.
        var link = $(this).find('a')[0];
        //Use the link we just found instead of this.
        //Also, instead of href, use pathname. That will give just the path, not the host.
        if(url == removeSlash(link.pathname)) {
            //This referes to the li, so we can keep this line of code as it is.
            $(this).addClass('active');
        }
    });
});
function removeSlash(url) {
    //Remove leading slash, if there is one.
    if(url.charAt(0) == '/') url = url.substring(1);
    //Remove trailing slash, if there is one.
    if(url.charAt(url.length-1) == '/') url = url.substring(0, url.length-1);
    //Return the result.
    return url;
}

工作 JSFiddle。请注意,在很多情况下,这可能不起作用。例如,我不确定如果当前URL http://example.com/site.php?x=4并且链接的href /site.php会发生什么。您应该能够通过修改 removeSlash 函数来实现处理此类情况的方法。

试试下面的方法。它查找以当前 URL 作为其href的链接,查找其父元素,并将类应用于父元素。

$(document).ready(function() {
    $('a[href="' + this.location.pathname + '"]').parent().addClass('active treeview-menu');
});