Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在使用javascript的不同页面上,如何更改单独header.html中的活动导航li?_Javascript_Jquery_Html_Header_Header Files - Fatal编程技术网

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

在使用javascript的不同页面上,如何更改单独header.html中的活动导航li?,javascript,jquery,html,header,header-files,Javascript,Jquery,Html,Header,Header Files,我有一个6页的网站,其中标题在一个单独的文件中。我希望导航链接被突出显示为活动的,这取决于我在哪个页面上 这是header.html中的主导航: <div id="fh5co-main-nav"> <nav id="fh5co-nav" role="navigation"> <ul class="nav"> <li class="active"><a href="index.html">H

我有一个6页的网站,其中标题在一个单独的文件中。我希望导航链接被突出显示为活动的,这取决于我在哪个页面上

这是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>

…但我似乎不明白为什么它不起作用。任何人能提出的任何建议都将不胜感激

您的定位点是相对路径,即
href=“contact.html”
,因此您正在使用的选择器
[href=“/”+pathname+”]
将不匹配任何路径,除非您更改定位点的值以包含前面的斜杠

$.load
接受回调函数,该函数允许您在将资源加载到DOM中后执行逻辑

回调中的此
被设置为应用了
load
方法的DOM元素,即
#头

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