在使用 javascript 的不同页面上时,如何在单独的 header.html 中更改活动导航栏?

How do I change the active nav li in separate header.html when on different pages using javascript?

我有一个包含 6 个页面的站点,其中 header 在一个单独的文件中。我希望根据我所在的页面将导航链接突出显示为活动链接。

这是来自 header.html 的主导航:

<div id="fh5co-main-nav">
    <nav id="fh5co-nav" role="navigation">
        <ul class="nav">
            <li class="active"><a href="index.html">Home</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="products.html">Products</a></li>
            <li><a href="location.html">Location</a> </li>
            <li><a href="cafe.html">Cafe</a></li>
            <li><a href="contact.html">Contact</a></li>
        </ul>
    </nav>
</div>

它在每个页面中的链接是这样的:

<div id="header"></div>

在我的 main.js 我有这个:

$(function(){
    $("#header").load("header.html"); 
    $("#footer").load("footer.html"); 
  });
$(document).ready(function() {
    // get current URL path and assign 'active' class
    var pathname = window.location.pathname;
    $('ul.nav li > a[href="/'+pathname+'"]').parent().addClass('active');
});

...但我似乎无法弄清楚为什么它不起作用。任何人都可以提供任何建议,我们将不胜感激!!

您的锚点是相对路径,即 href="contact.html",因此您使用的选择器 [href="/'+pathname+'"] 将不匹配它们中的任何一个,除非您将锚点的值更改为包含前面的斜杠。

$.load 接受一个回调函数,允许您在加载资源后执行逻辑插入到 DOM.

回调中的

this 设置为应用 load 方法的 DOM 元素,即 #header.

window.location.pathname 将始终包含首字母 '/',因此无需在选择器中添加前缀。

我还加入了一些逻辑来切换同级元素的活动状态。

$(function(){
  $('#header').load('header.html', function () {
    $('.nav a[href="' + window.location.pathname + '"]', this).parent().addClass('active').siblings().removeClass('active');
  }); 
  $('#footer').load('footer.html'); 
});