主动仅应用于一个元素

时间:2018-07-19 17:15:17

标签: javascript html css twitter-bootstrap bootstrap-4

我正在使用jQuery将active添加到我的菜单中。它可以在索引页面上运行,但现在无法在其他页面上运行。我尝试更改网址以适合确切的location.pathname,但这似乎不起作用,因此我也尝试在其之前删除\。任何帮助,将不胜感激。

我的标记:

<nav class="sticky-top navbar navbar-expand-lg navbar-light bg-myColor">
    <a class="navbar-brand" href="#">
      <img src="image/VC-Logo.png" alt="Visionary Creatives logo" height="150px;" />
    </a>
    <button class="navbar-toggler navbar-brand" type="button" data-toggle="collapse" data-target="#navToggle" aria-controls="navToggle" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navToggle">
    <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
    </ul>
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="/">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/coming-soon.php">Web Design</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/coming-soon.php">Graphic Design</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/coming-soon.php">SEO &amp; Marketing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/coming-soon.php">About Us</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/coming-soon.php">Contact Us</a>
      </li>
    </ul>
  </div>
</nav>

和我的jQuery:

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

和我的网站(如果有帮助的话): http://www.visionary-creatives.com

1 个答案:

答案 0 :(得分:2)

当我浏览您网站的view-source页面时。我看到除index页以外的其余页面中,这些脚本在页面源末尾都缺失-

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script type ="text/javascript" src="js/lightbox.js"></script>
<script type="text/javascript" src="js/jQuery.js"></script>

请打开浏览器控制台,您将在那看到一些错误。因此,请添加上述脚本,以便您的代码可以运行到每个页面

您的代码是完美的并且可以正常运行。