将URL路径与<a>attr('href')来动态更新.active类

Matching the URL path with <a> attr('href') to dynamically update .active class

本文关键字:href 动态 更新 active attr 路径 URL lt gt      更新时间:2023-09-26

嘿,伙计们,我在navbar.php文件中有我的navbar代码,HTML看起来如下:

<nav role="navigation" class="nav" >
      <ul class="menu" id="menu">
        <li class="active"><a href="index.php">
        Home</a></li>
        <li><a href="about-us.php">About us</a></li>
        <li><a href="products.php">Products</a>
            <ul class="submenu">
                <li class="active">product-1</li>
                <li>product-2</li>
                <li>product-3</li>
                <li>product-4</li>
                <li>product-5</li>
                <li>product-6</li>
            </ul>
        </li>
        <li><a href="contactus.php">Contact us</a></li>
      </ul>
</nav>

在page load上,我运行了一个非常简单的Jquery片段来运行所有的<a>,并检查其href是否与浏览器中的url(实际上是url的末尾,例如index.php)匹配。

所以我有以下Jquery片段:

 $(document).ready(function(){
var _urlpath = $(location).attr('pathname');
            console.log(_urlpath);  // this does't print out the desired version , it prints `/lala-v1/about-us.php"`
        $('#menu > li').each(function(){
            var _str = $(this).find('a').attr('href');
            console.log(_str); // these print out the desired output eg. index.php
            if(_str == _urlpath){
                console.log(_str + _urlpath);
            }
        });
});

检查我的评论,我的困难是在Jquery的第二行获得正确的url路径。我浏览了这篇文章,我看到的Jquery选项都不会返回我看到的URL的末尾部分。

那我该怎么办?我被卡住了,在JS/Jquery中有办法解决这个问题吗。

我对这两个领域都是新手,所以我很感激任何帮助。

试试这个:

var _urlpath = window.location.pathname.split('/').pop();
// or: $(location).attr('pathname').split('/').pop();

使用prop()而不是attr(),它将返回绝对路径,而不是为属性设置的字符串。

比较文件名可能会失败,不同目录中可能存在名称相同的文件。

$(document).ready(function(){
        $('#menu > li').each(function(){
            var _str = $(this).find('a').prop('href');
            if(_str == location.href){
                $(this).css('background','red');
            }
        });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="menu" id="menu">
        <li class="active"><a href="index.html">
        Home</a></li>
        <li><a href="about.html">About us</a></li>
        <li><a href="">This is the current page, should be highlighted by jquery</a></li>
        <li><a href="products.html">Products</a>
            <ul class="submenu">
                <li class="active">product-1</li>
                <li>product-2</li>
                <li>product-3</li>
                <li>product-4</li>
                <li>product-5</li>
                <li>product-6</li>
            </ul>
        </li>
        <li><a href="contactus.html">Contact us</a></li>
      </ul>

这些值不匹配,因为/lala-v1/about-us.php !== about-us.html,加上您使用".php"提供的页面和链接都是".html"。您可以使用它来获得正确的值:window.location.pathname.split('/').pop();