简体   繁体   中英

How can I add the active class to to the current <li> within bootstrap collapse navbar-collapse?

I am trying to use javascript in order to create a bootstrap <div class="navbar navbar-inverse navbar-fixed-top"> where I only have to update the javascript file rather than manage a navbar on individual pages for a website.

This is the code for the banner:

 document.write( " <div class='navbar navbar-inverse navbar-fixed-top'>" + " <div class='container'>" + " <div class='navbar-header'>" + " <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>" + " <span class='icon-bar'></span>" + " <span class='icon-bar'></span>" + " <span class='icon-bar'></span>" + " </button>" + " <a class='navbar-brand' href='link1.aspx'>My Website</a>" + " </div>" + " <div class='collapse navbar-collapse'>" + " <ul class='nav navbar-nav'>" + " <li><a href='link1.aspx'>Link 1</a></li>" + " <li><a href='link2.aspx'>Link 2</a></li>" + " <li><a href='link3.aspx'>Link 3</a></li>" + " <li><a href='link4.aspx'>Link 4</a></li>" + " <li><a href='link5.html'>Link 5</a></li>" + " <li><a href='link6.aspx'>Link 6</a></li>" + " </ul>" + " </div>" + " <!--/.nav-collapse -->" + " </div>" + " </div>" ); 

This is where I am trying to set the current page's navigation bar <li> to active:

 $(document).ready(function () { $(".collapse navbar-collapse ul li a").each(function () { if ($(this).attr("href") == window.location.pathname) $(this).addClass("active"); }) }) 

All code is located in a header.js file that I call from each page at the beginning to show the header:

 <html> <body> <script type="text/javascript" src="Scripts/header.js"></script> </body> </html> 

The problem is the code doesn't work and I don't know why. Am I declaring $(".collapse navbar-collapse ul li a") incorrectly? Is the way that the navigation bar setup incorrect?

You have this HTML:

<div class='collapse navbar-collapse'>

And you are using this JS:

$(".collapse navbar-collapse ul li a")

Try changing the above line to this:

$(".collapse ul li a")

...or...

$(".collapse.navbar-collapse ul li a")

Also, your if statement looks poorly structured.

Try changing this:

if ($(this).attr("href") == window.location.pathname)
    $(this).addClass("active");

To this:

if ($(this).attr("href") == window.location.pathname) {
    $(this).addClass("active");
}

That may or may not solve your problem, but nonetheless it should fix some errors in your code.

Since collapse and navbar-collapse are in the same element you have to write

$(".collapse.navbar-collapse ul li a")

In the provided code there was no jQuery .js file included, but I assume you have that in your own code

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