jQuery 活动菜单 link 索引页面始终处于活动状态

jQuery active menu link to index page is always active

我有一个菜单,使用下面的 jQuery 添加 class 活动以突出显示当前页面。

<script>
    jQuery(document).ready(function($) {
        $(function() {
            setNavigation();
        });

        function setNavigation() {
            var path = window.location.pathname;
            path = path.replace(/\/$/, "");
            path = decodeURIComponent(path);

            $(".nav a").each(function() {
                var href = $(this).attr('href');
                if (path.substring(0, href.length) === href) {
                    $(this).closest('li').addClass('active');
                }
            });
        }
    });
</script>

这是我的 HTML:

<ul class="nav">
    <li><a href="/wordpress">Portfolio One</a></li>
    <li><a href="/wordpress/portfolio-two">Portfolio Two</a></li>
    <li><a href="/wordpress/portfolio-three">Portfolio Three</a></li>
    <li><a href="/wordpress/bio-contact">Bio / Contact</a></li>
</ul>

如您所见,第一个 link(投资组合一)链接到主页。这导致此 link 始终具有 class 活动状态,无论菜单位于哪个页面。

任何人都可以提供一些见解来修改我的 jQuery 以使其获得完整的 link 并仅排除部分匹配吗?

在添加 class

之前在 if-construct 中包含另一个条件如何?

if (path.substring(0, href.length) === href && path.length == href.length)

菜单中的 link 总是有活动的 class 的原因是它不会因为不活动的 link 而被删除。 您可以尝试添加 $('.nav li').removeClass('active'); 这将首先删除 active class 然后您可以为当前活动 link.[=13= 添加活动 class ]

这是更新后的代码。

function setNavigation() {
    var path = window.location.pathname;
    path = path.replace(/\/$/, "");
    path = decodeURIComponent(path);

    $(".nav a").each(function() {
        $('.nav li').removeClass('active'); // remove active for all links
        var href = $(this).attr('href');
        if (path.substring(0, href.length) === href) {
            $(this).closest('li').addClass('active');
        }
    });
}