简体   繁体   中英

Getting navigation to display the selected page

I'm struggling with getting my navigation menu to show the selected page. I'm using the Bootstrap framework to build my site. This is my navigation menu:

<nav class="navbar">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/index.html">Digital Transformation</a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav pull-right">
        <li class="active"><a href="/index.html">Transformation deck</a></li>
        <li><a href="/backgroundInformation.html">Background information</a></li>
      </ul>
    </div><!--/.nav-collapse -->
  </div>
</nav>

As far as I can tell, Bootstrap uses the following JS to make the selected menu item active, which I have in my header:

    <script>
      $('label').click(function() {
        $(this).parent('li').toggleClass('active');
      });
    </script>

However with this code my primary nav item is active on page load, but when I select the second item it keeps 'Tranformation deck' as active instead of 'Background information'.

Am I missing a trick here? Any help would be greatly appreciated.

If you want to hook up click listeners to your nav items, your script should be something like this:

<script>
  $('#navbar nav li a').click(function() {
    $(this).parent('li').toggleClass('active');
  });
</script>

You don't have any 'label' tags in your code, so there isn't anything to attach click event handlers to.

  $(function() { // this will get the full URL at the address bar var url = window.location.href; // passes on every "a" tag $("#navbar a").each(function() { // checks if its the same on the address bar if (url == (this.href)) { $(this).closest("li").addClass("active"); } }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM